简体   繁体   English

根据数据框中的条件填写新列

[英]Filling in a new column based on a condition in a data frame

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 ; 我想在数据框中添加新列,以便对于每一行,如果LOC == 1V等于为V1给出的值; if LOC==2 then V is equal to the value given for V2 . 如果LOC==2V等于为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. 我需要有关如何在R中执行此操作的帮助。

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

如果LOC仅包含1或2,那么它将起作用

 df$V <- ifelse(df$LOC == 1, df$V1, df$V2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM