根据数据框中的条件填写新列 [英] Filling in a new column based on a condition in a data frame
本文介绍了根据数据框中的条件填写新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
LOC == 1
然后 V
等于 V1
给出的值;如果 LOC == 2
然后 V
等于 V2
。这是一个例子: df < -
LOC V1 V2
1 0.5 0.7
1 0.5 0.7
2 0.5 0.7
1 0.6 0.8
结果应为:
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
我需要帮助如何在R中执行此操作。
解决方案
如果 LOC
包含1或2,那么这将工作
df $ V< - ifelse(df $ LOC == 1,df $ V1 ,df $ V2)
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.
解决方案
If LOC
only contains 1 or 2 then this will work
df$V <- ifelse(df$LOC == 1, df$V1, df$V2)
这篇关于根据数据框中的条件填写新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文