3

I want to add a new column in my data frame so that for each row if LOC == 1 then V is equal to the value given for V1; if LOC==2 then V is equal to the value given for V2. Here is an example:

df <- 
LOC   V1   V2
 1    0.5  0.7
 1    0.5  0.7
 2    0.5  0.7
 1    0.6  0.8

Result should be:

df <-
 LOC   V1   V2   V
 1    0.5  0.7   0.5
 1    0.5  0.7   0.5
 2    0.5  0.7   0.7
 1    0.6  0.8   0.6

I need help on how to do that in R.

Jaap
  • 81,064
  • 34
  • 182
  • 193
daragh
  • 173
  • 1
  • 11

2 Answers2

4

Use matrix indexing:

idx <- cbind(seq_len(nrow(dat)), dat$LOC)
#      row  col
#     [,1] [,2]
#[1,]    1    1
#[2,]    2    1
#[3,]    3    2
#[4,]    4    1

dat[-1][idx]
#[1] 0.5 0.5 0.7 0.6
thelatemail
  • 91,185
  • 12
  • 128
  • 188
4

If LOC only contains 1 or 2 then this will work

 df$V <- ifelse(df$LOC == 1, df$V1, df$V2)
Jacob H
  • 4,317
  • 2
  • 32
  • 39