[R] for loop

arun smartpink111 at yahoo.com
Tue Nov 13 03:15:58 CET 2012


HI,
You can do this in many ways:
dat1<-read.table(text="
med1,med2,med3     
 1,0,1       
0,1,1    
2,0,0 
",sep=",",header=TRUE)   
#1st method
library(reshape)

dat2<-melt(dat1)
dat3<-aggregate(dat2$value,by=list(dat2$variable),sum)
 colnames(dat3)<-c("name","sum(n11)")
 dat3
#  name sum(n11)
#1 med1        3
#2 med2        1
#3 med3        2


#2nd method
res<-data.frame(colSums(dat1)) 
 names(res)<-"sum(n11)"
 res
#     sum(n11)
#med1        3
#med2        1
#med3        2


#3rd method
 do.call(rbind,lapply(dat1,sum))
#     [,1]
#med1    3
#med2    1
#med3    2

A.K.




________________________________
From: farnoosh sheikhi <farnoosh_81 at yahoo.com>
To: arun <smartpink111 at yahoo.com> 
Sent: Monday, November 12, 2012 7:24 PM
Subject: for loop


Hi there,

I want to calculate the odds ratio for a data like below.
 I want to compute the sum of each column as a new column and variable names as a new column.
I have about 1000 variables and I think I need to write a loop.

med1    med2    med3     
 1              01       
011
200       


The final data will look like:
name        sum(n11)
med1         3
med2          1
med3          2


Thanks a lot :-).
Best,Farnoosh Sheikhi



More information about the R-help mailing list