Skip to content

Seeking help with a loop

3 messages · Greg Blevins, Tony Plate, Jean Eid

#
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
#
> 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:
#
You can do the following without resorting to a "hard coded" loop
sapply( paste("q35", letters[1:grep("r", letters)], sep=""), function(x)
ifelse(temp[, x]%in%1,temp[, sub("5", "3", x)],NA)


as the following example shows
temp <- matrix(sample(c(0,1), 360, replace=T), nrow=10)
 colnames(temp) <- c(paste("q33", letters[1:grep("r", letters)], sep=""), paste("q35", letters[1:grep("r", letters)], sep=""))
 sapply( paste("q35", letters[1:grep("r", letters)], sep=""), function(x)  ifelse(temp[, x]%in%1,temp[, sub("5", "3", x)],NA))


HTH

Jean
On Wed, 3 Aug 2005, Greg Blevins wrote: