Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用dplyr有条件地将一列中的值替换为另一列中的值_R_Replace_Dplyr_Conditional - Fatal编程技术网

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

使用dplyr有条件地将一列中的值替换为另一列中的值,r,replace,dplyr,conditional,R,Replace,Dplyr,Conditional,我想用不同列中同一行中的值替换一列中与特定条件匹配的值。考虑这个例子: 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, X

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

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))
库(tidyverse)

数据使用
replace
,长度应该相同,因此我们需要将
其他
以及逻辑表达式子集

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

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

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

@是的,你是对的。一般来说,在执行此操作之前,最好将
因子
转换为
字符
。转换或使用
ifelse(as.character(X25)=“Other”、as.character(Other)、as.character(X25))
或必须在
转换之前添加
级别(如果有一些新级别),如