vashts85
vashts85

Reputation: 1147

r: dynamic data frame looping

I have a dataset that looks like this:

   own_cc.1 own_cc.2 own_cc.3 own_cc.4 own_cc.5 own_cc.6 own_cc.7
1         1        0        1        0        1        0        0
2         1       NA        1        1        1        1       NA
3         0        0        1        0        0        0        0
4         1        0       NA        0        1       NA       NA
5         1        0        1        1        0        0        0
6         0        0        0        0        0        1        0
7         1        0        0        0        0        0        0
8         1        1        0        0        0        0        1
9         0        0        1        0        0        0        0
10        0        0        0        0        0        1        0

And what I would like to do is create a new variable for every combination of own_cc.1 and the other variables. So, the function is r_own_2 <- ifelse(own_cc.1==0 own_cc.2==1,1,0) and it should just switch out the r_own_ and own_cc.2parts.

I tried doing this with a loop but it's not working:

for(i in 2:7) {
  nam <- paste("r_own_", i, sep = "")
  w[nam] <- NA
  w[nam] <- with(w, ifelse(own_cc.1==0 & get(nam)==1,1,0))
}

Is there a way to do this with a loop? Should I use a list? If so, could you kindly provide detailed instructions as lists are relatively new to me?

Upvotes: 0

Views: 179

Answers (1)

akrun
akrun

Reputation: 886938

We can do this without using ifelse and without the get part. As paste is vectorized function, we can create the 'nam' outside the loop

nam <- paste0("r_own_", 2:7)

Then loop through the columns of 'w' except the 1st, compare the logical vectors (w[,1]==0) with x==1, coerce it to binary with as.integer, and assign the list output to create the new columns specified in 'nam'

w[nam] <- lapply(w[-1], function(x)  as.integer((w[,1]==0) & (x==1)))

Upvotes: 1

Related Questions