[R] Seeking help with a loop

Tony Plate tplate at acm.org
Wed Aug 3 18:00:52 CEST 2005


 > x <- data.frame(q33a=3:4,q33b=5:6,q35a=1:2,q35b=2:1)
 > y <- list()
 > for (i in grep("q33", colnames(x), value=TRUE))
+    y[[sub("q33","",i)]] <- ifelse(x[[sub("q33","q35",i)]]==1, x[[i]], NA)
 > as.data.frame(y)
    a  b
1  3 NA
2 NA  6
 > # if you really want to create new variables rather
 > # than have them in a data frame:
 > # (use paste() or sub() to modify the names if you
 > #  want something like "newfielda")
 > for (i in names(y)) assign(i, y[[i]])
 > a
[1]  3 NA
 > b
[1] NA  6
 >

hope this helps,

Tony Plate

Greg Blevins wrote:
> Hello R Helpers,
> 
> After spending considerable time attempting to write a loop (and searching the help archives) I have decided to post my problem.  
> 
> In a dataframe I have columns labeled:
> 
> q33a q33b q33c...q33r    q35a q35b q35c...q35r
> 
> What I want to do is create new variables based on the following logic:
> newfielda <- ifelse(q35a==1, q33a, NA)
> newfieldb <- ifelse(q35b==1, q33b, NA)
> ...
> newfieldr
> 
> What I did was create two new dataframes, one containing q33a-r the other q35a-r and tried to loop over both, but I could not get any of the loop syntax I tried to give me the result I was seeking.
> 
> Any help would be much appreciated.
> 
> Greg Blevins
> Partner
> The Market Solutions Group, Inc.
> Minneapolis, MN
> 
> Windows XP, R 2.1.1
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list