[R] For loop with ifelse help

David Winsemius dwinsemius at comcast.net
Wed Sep 22 17:59:01 CEST 2010


On Sep 22, 2010, at 11:42 AM, Pele wrote:

>
> Hello R users,
>
> I have 2 files (file1 and f2) and I am trying to sum columns 6:10 of a
> specific row in f2 and append it in
> file 1 if the "state" variable in file 1 equals the rowname in f2.   
> Below is
> an example of the code I wrote
> using a for loop, but it not working (i.e it only works for the last  
> number
> (10) in the loop). Can someone tell me how to fix?
>
> Many thanks !
>
> file1 <- data.frame(ID=seq(1:30), state=sample(1:10, 30,  
> replace=TRUE));
> file1
>   ID state
> 1   1     7
> 2   2     7
> 3   3     6
> 4   4     4
> 5   5     5
> 6   6     7
> 7   7    10
> 8   8     1
> 9   9     1
> 10 10     5
> ............
> .........
>
> file2 <- matrix(seq(1:100),nrow=10)
>  f2 <- as.data.frame(file2); f2
>   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
> 1   1 11 21 31 41 51 61 71 81  91
> 2   2 12 22 32 42 52 62 72 82  92
> 3   3 13 23 33 43 53 63 73 83  93
> 4   4 14 24 34 44 54 64 74 84  94
> 5   5 15 25 35 45 55 65 75 85  95
> 6   6 16 26 36 46 56 66 76 86  96
> 7   7 17 27 37 47 57 67 77 87  97
> 8   8 18 28 38 48 58 68 78 88  98
> 9   9 19 29 39 49 59 69 79 89  99
> 10 10 20 30 40 50 60 70 80 90 100
>
>
> for (i in length(f2)) {
> file1$chksum <- ifelse ((file1$state==rownames(f2)[i]),
> rowSums(f2[rownames(f2)[i], 6:10]), 0)
>                      }

That looks overly complex and inefficient (not to mention wrong):

Try:
res <- merge(file1, rowSums(file2), by.x="state", by.y="row.names",  
all=TRUE)
names(res)[4] <- "chksum"

If you need it sorted by ID then:

res[order(res$ID],]

-- 
David.

>  print(file1)
>   ID state chksum
> 1   1     7      0
> 2   2     7      0
> 3   3     6      0
> 4   4     4      0
> 5   5     5      0
> 6   6     7      0
> 7   7    10    400
> 8   8     1      0
> 9   9     1      0
> 10 10     5      0
> 11 11    10    400
> 12 12     9      0
> 13 13    10    400
> 14 14     9      0
> 15 15     5      0
> 16 16     3      0
> 17 17     1      0
> 18 18     7      0
> 19 19     7      0
> 20 20     2      0
> 21 21     3      0
> 22 22     8      0
> 23 23     8      0
> 24 24     4      0
> 25 25     6      0
> 26 26     6      0
> 27 27     3      0
> 28 28     3      0
> 29 29     5      0
> 30 30     5      0
> -- 
> View this message in context: http://r.789695.n4.nabble.com/For-loop-with-ifelse-help-tp2550547p2550547.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list