Saturday 15 June 2013

how to write this in a for loop in R? -



how to write this in a for loop in R? -

i have wrote

pp1<-table(sip$newss4_1 [sip$newss4_1==1], sip$hs1c1 [sip$newss4_1==1]) pp1=round(prop.table(pp1,1), digits=3) pp1

i have 30 variables do. example:

pp2<-table(sip$newss4_2 [sip$newss4_2==1], sip$hs1c1 [sip$newss4_2==1]) pp2=round(prop.table(pp2,1), digits=3) pp2

and pp3...pp30 on. havenewss4_1...newss4_30in dataframe already.

how write in loop?

thanks.

it seems making things hard yourself.

instead of creating 30 variables different names, why not utilize single list? instead of using column names, why not utilize column numbers?

pp <- list() colnums <- grep(names(sip), "newss4_") # assuming in order (i in 1:30) { cn <- colnums[i] pp[[i]] <- table(sip[,cn ] [sip[,cn]==i], sip$hs1c1 [ sip[,cn]==i ]) }

if want have different variables, can utilize

assign(paste0("pp", i), value)

to assign e.g. pp1, pp2, etc.

for-loop

No comments:

Post a Comment