2

This might be a simply question but I haven't figured it out.

I am writing a simple loop.

v6<-c()
> aa
 [1]   1   4   8   9  10  12  15  16  17  18  19  20  21  25  29  30  38
[18]  39  46  47  48  49  52  53  54  60  65  69  73  75  81  82  83  85
[35]  86  87  90  91  92  94  96  97  98  99 100 101 104 105 106 110 112
[52] 113 114 116 117 118 119 122 125 126 128 129
for (i in aa){
  v6[i]<-sum(as.numeric(Sep1$Units[Sep1$ID==i]))   
}
> v6
  [1]  3800    NA    NA  2600    NA    NA    NA  7700 13500 11900    NA
 [12] 15600    NA    NA  2000 17700  9600 11600  3400 11200  6600    NA
 [23]    NA    NA  6000    NA    NA    NA  8800  2400    NA    NA    NA
 [34]    NA    NA    NA    NA  2600  4500    NA    NA    NA    NA    NA
 [45]    NA 23400 36000  4000  5100    NA    NA  9200  5400  7000    NA
 [56]    NA    NA    NA    NA  5000    NA    NA    NA    NA 60000    NA
 [67]    NA    NA  7200    NA    NA    NA 20000    NA 39600    NA    NA
 [78]    NA    NA    NA 23600  1600 10600    NA 39000  1000  6200    NA
 [89]    NA  3000   100  1400    NA 12800    NA  5100  2000 32000  7000
[100] 10900  4800    NA    NA  3200 14600 24000    NA    NA    NA 16200
[111]    NA  5000 28800 16800    NA  2600 40000   800  8400    NA    NA
[122] 18000    NA    NA 24800 13600    NA  4600 11700

I realized R has red 1 through 129 instead of just read "1, 4, 8, ...". Now I know I can use na.omit(v6) to remove all the NA in values, but I am just wondering if there is a way that allows R to ready just the values in "aa" instead of going through 1 though 129 please?

I don't know if I have emphasized my question well. Thanks

jub0bs
  • 60,866
  • 25
  • 183
  • 186
Noah Xu
  • 167
  • 3
  • 11

1 Answers1

1

Generally if you are using a for loop in R there is always a better way to do it.

You need to provide test data in order for me to show that this works, but I believe the following statement will do what you want without a for loop:

v6[aa] <- sum(as.numeric(Sep1$Units[Sep1$ID %in% aa]))

The expression "v6[aa] <-" says "for the elements in the vector v6 at the positions in the vector aa, assign the values in the following vector to those positions."

patrickmdnet
  • 3,332
  • 1
  • 29
  • 34
  • Thanks!!!! This helps. Sorry that I did not provide the test data. But I do understand what you are saying. Thanks a bunch. – Noah Xu Nov 09 '15 at 14:59
  • I just want to read the values that has the ID number corresponding to the set "aa" instead of going through the rang of the set "aa". I think my code is letting R going though the rang of "aa" instead of only reading the values that has the ID number corresponding to the set "aa". But yes, I think yours are what I am looking for. Thanks again – Noah Xu Nov 09 '15 at 15:01