使用dplyr有条件地将一列中的值替换为另一列中的值

使用dplyr有条件地将一列中的值替换为另一列中的值

本文介绍了使用dplyr有条件地将一列中的值替换为另一列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用另一列中同一行中的值替换匹配特定条件的一列中的值.考虑以下示例:

I want to replace the values in one column that match a certain condition with values in that same row from a different column. Consider this example:

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(作为较长的mutate/summary过程的一部分)?

The code using "within" works well. How can I use dplyr if needed (as part of a longer mutate / summarise process)?

这与用dplyr更改变量的值不同..我不想盲目地为所有匹配的单元格分配相同的值(例如NA).我想从另一个特定的列中提取它们.

This is a different scenario from Change value of variable with dplyr. I don't want to blindly assign all matching cells with the same value (e.g., NA). I wanted to pull them from another particular column.

推荐答案

使用 replace ,长度应相同,因此我们还需要对 Other 进行子集化带有逻辑表达式

With replace, the lengths should be the same, so we need to subset the Other as well with the logical expression

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))

这篇关于使用dplyr有条件地将一列中的值替换为另一列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 18:07