【发布时间】:2016-02-05 12:22:00
【问题描述】:
我的数据框:
class columnA
foo 10
bar 14.2
hello 48695
bar 4
foo -7
我正在尝试执行以下操作:
if (my_df$class== "foo") {
my_df$columnB <- my_df$columnA * 2
}else{
if (my_df$class == "bar") {
my_df$columnB <- my_df$columnA * 5
}else{
my_df$columnB <- my_df$columnA * 10
}
}
编辑:我也试过这个:
ifelse (my_df$class== "foo",
my_df$columnB <- my_df$columnA * 2
ifelse (my_df$class== "bar",
my_df$columnB <- my_df$columnA * 5,
my_df$columnB <- my_df$columnA * 10
)
)
由于它不起作用,让我用伪代码说明它:
for each row,
if the value in column class is "foo"
set the value in column B to be 2 times the value in column A
if the value in column class is "bar"
set the value in column B to be 5 times the value in column A
if the value in column class is something else
set the value in column B to be 10 times the value in column A
当然,我的问题是分配运算符:如果我使用<-,整个columnB 列最终会是columnA 乘以5(因为碰巧class 的值是最后一行是bar)。
有什么办法吗?
我将采取一个解决方案来解决我的问题,而无需通过 if/elseif/else 语法,但如果有人能提供一个保持这种语法的解决方案,我也会非常感激,以便学习。
谢谢
【问题讨论】:
-
你能给我们一份你的数据样本吗(使用
dput())?
标签: r if-statement dataframe