【问题标题】:Conditionally replace values in one column with values from another column using dplyr [duplicate]使用 dplyr [重复] 有条件地将一列中的值替换为另一列中的值
【发布时间】:2018-10-18 16:09:38
【问题描述】:

我想用不同列中同一行中的值替换与特定条件匹配的列中的值。考虑这个例子:

library(tidyverse)
data <- tribble(
  ~X25, ~Other,
  "a", NA,
  "b", NA,
  "Other", "c",
  "Other", "d"
)
View(data)

# Works to change values in X25
within(data, {
    X25 <- ifelse(X25 == "Other", Other, X25)
})

# Changes values in X25 to NA and doesn't replace X25 with appropriate value from Other column
data %>% mutate(X25 = replace(X25, X25 == "Other", Other))

使用“内部”的代码运行良好。如果需要(作为更长的变异/汇总过程的一部分),我如何使用 dplyr?

编辑:这是与Change value of variable with dplyr 不同的场景。我不想盲目地为所有匹配的单元格分配相同的值(例如,NA)。我想把它们从另一个特定的列中拉出来。

【问题讨论】:

    标签: r replace dplyr conditional


    【解决方案1】:

    对于replace,长度应该相同,所以我们需要用逻辑表达式对Other进行子集化

    data %>%
        mutate(X25 = replace(X25, X25 == "Other", Other[X25=="Other"]))
    

    另一个选项是case_when

    data %>%
         mutate(X25 = case_when(X25=="Other"~ Other,
                                TRUE ~ X25))
    

    ifelse

    data %>%
        mutate(X25 = ifelse(X25 == "Other", Other, X25))
    

    【讨论】:

    • @stevec 是的,你是对的。一般来说,最好在执行之前将factor 转换为character。转换或使用ifelse(as.character(X25) == "Other", as.character(Other), as.character(X25))),否则必须在case_when等转换之前添加levels(如果有一些新级别)
    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 2021-09-23
    • 2019-04-20
    • 2020-08-13
    • 2016-06-07
    • 2012-11-06
    • 1970-01-01
    • 2019-12-04
    相关资源
    最近更新 更多