【问题标题】:Replace a value in a dataframe with a value in another column, based on a condition on a third column根据第三列的条件,将数据框中的值替换为另一列中的值
【发布时间】: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

当然,我的问题是分配运算符:如果我使用&lt;-,整个columnB 列最终会是columnA 乘以5(因为碰巧class 的值是最后一行是bar)。

有什么办法吗?

我将采取一个解决方案来解决我的问题,而无需通过 if/elseif/else 语法,但如果有人能提供一个保持这种语法的解决方案,我也会非常感激,以便学习。

谢谢

【问题讨论】:

  • 你能给我们一份你的数据样本吗(使用dput())?

标签: r if-statement dataframe


【解决方案1】:

if 没有矢量化,因此您可以尝试使用ifelse

例如

my_df$columnB=ifelse(my_df$class== "foo",my_df$columnA * 2, 
                 ifelse(my_df$class == "bar",my_df$columnA * 5,my_df$columnA * 10))

【讨论】:

  • 该死的我是个白痴...查看我编辑的问题以查看我也尝试过的类似事情,这显然与分配运算符有相同的问题。谢谢!
【解决方案2】:

使用 dplyr 包,您可以这样做:

my_df <- my_df %>%
mutate(columnB = ifelse(class == "foo", columnA*2,
                 ifelse(class == "bar", columnA*5, columnA*10)
                 )
       )

【讨论】:

  • 我不知道您的数据有多大,所以这可能无关紧要,但这也可能是迄今为止提供的最快的解决方案(尽管 data.table 可能占上风)。 dplyr 很适合尽早学习!非常直观和整洁。
【解决方案3】:

除了使用嵌套的ifelse,您还可以使用索引和数学的组合:

indx <- (mydf$class == "foo") + 1L + (mydf$class == "bar")*2
mydf$colB <- mydf$columnA*c(10, 2, 5)[indx]

给出:

> mydf
  class columnA   colB
1   foo    10.0     20
2   bar    14.2     71
3 hello 48695.0 486950
4   bar     4.0     20
5   foo    -7.0    -14

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 2021-10-01
    • 2022-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多