Search code examples
rfor-loopnested-loops

R for loop: For all groups of rows with the same value in column, do


I would love some help understanding the syntax needed to do a certain calculation in R.

I have a dataframe like this:

a b c
1 1 0
2 1 1
3 1 0
4 2 0
5 2 0
6 3 1
7 3 0
8 3 0
9 4 0

and I want to create a new column "d" that has a value of 1 if (and only if) any of the values in column "c" equal 1 for each group of rows that have the same value in column "b." Otherwise (see rows 4,5 and 9) column "d" gives 0.

a b c d
1 1 0 1
2 1 1 1
3 1 0 1
4 2 0 0
5 2 0 0
6 3 1 1
7 3 0 1
8 3 0 1
9 4 0 0

Can this be done with a for loop? If so, any advice on how to write that would be greatly appreciated.


Solution

  • Since you asked for a loop:

    # adding the result col
    dat <- data.frame(dat, d = rep(NA, nrow(dat)))
    
    # iterate over group
    for(i in unique(dat$b)){
      # chek if there is a one for 
      # each group
      if(any(dat$c[dat$b == i] == 1))
         dat$d[dat$b == i] <- 1
      else
        dat$d[dat$b == i] <- 0
    }
    

    of course the data.table solutions is more elegant ;)