r - Calculating number of values less than x by row of data frame -


i have searched forums , web high , low last 2 days, , broken down script try , find issue, reason, can't work beyond first row:

numbers <- mtcars[1:6,]  nnn <- c(1:(nrow(numbers)))  (i in nnn){   ly <- numbers[i,]   numbers[i,12]<- sum(abs(ly) < 5e0) } 

this returns:

> numbers                    mpg cyl disp  hp drat    wt  qsec vs gear carb v12 mazda rx4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4   6 mazda rx4 wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4  na datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1  na hornet 4 drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1  na hornet sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2  na valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1  na 

as can see, when 1, ly mazda rx4 row, , performs

sum(abs(ly) < 5e0) 

correctly, placing value 6 in new 12th column. however, beyond that, though i've determined looping through correctly, , returning ly correctly each iteration of i, not calculating sum part rows 2:5

its obvious doing wrong here, life of me can't pick it. i'm new r , programming, self taught pretty much, , i've written quite few successul loops , scripts far in last few weeks, has me dumfounded. else in our research group uses matlab went through me, problem down same did, , couldn't figure out why wouldn't work either.

i've used mtcars far test loop , accessible on forum. once know works, i'll translate dataset (which quite large).

using loops not necessary in r. more r-like solution use apply:

apply(numbers, 1, function(x) sum(abs(x) < 5e0))         mazda rx4     mazda rx4 wag        datsun 710    hornet 4 drive                 6                 6                 7                 6 hornet sportabout           valiant                 6                 6 

adding column involves:

numbers$v12 = apply(numbers, 1, function(x) sum(abs(x) < 5e0)) 

some remarks on code:

  • there no need wrap 1:(nrow(numbers)) c.
  • generating index vector can more done using seq_len, i.e. seq_len(nrow(numbers)).

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -