条件筛选器一列并在新列中更新同一行

时间:2018-12-07 01:26:26

标签: r

是否可以在一个列中进行条件过滤,然后更新另一列但行位置相同的条件?

这是一个可复制的示例:

df <- data.frame(name = c("Tom", "Harry", "Charles"), Amount = c(30, -30, 49), Budget = c(51, 53, 55))

     name Amount Budget
1     Tom     30     51
2   Harry    -30     53
3 Charles     49     55

例如,我试图过滤出“金额”列下所有低于0的值,并为哈利更新预算列(替换现有值)。

     name Amount Budget
1     Tom     30     51
2   Harry           -30
3 Charles     49     55

有人能指出我正确的方向吗?谢谢!

2 个答案:

答案 0 :(得分:1)

我们可以做到

#Find out indices where Amount is less than 0
inds <- df$Amount < 0

#Replace the corresponding Budget value by Amount value
df$Budget[inds] <- df$Amount[inds]

#Change the Amount to 0
df$Amount[inds] <- 0 #Replacing it with 0 since it's a numeric column

df

#     name Amount Budget
#1     Tom     30     51
#2   Harry      0    -30
#3 Charles     49     55

答案 1 :(得分:1)

这是一个dplyr解决方案。首先,我创建数据框。

df <- data.frame(name = c("Tom", "Harry", "Charles"), 
                 Amount = c(30, -30, 49), 
                 Budget = c(51, 53, 55))

接下来,如果Budget小于零,我将Amount设置为Amount,如果Amount小于NA则将Amount设置为df %>% mutate(Budget = ifelse(Amount < 0, Amount, Budget), Amount = ifelse(Amount < 0, NA, Amount)) 大于零。

#      name Amount Budget
# 1     Tom     30     51
# 2   Harry     NA    -30
# 3 Charles     49     55

给予

Amount

当然,可以根据需要将NA设置为零,而不是unset