R在其他字符列和查找字符向量的条件下变异字符列

时间:2018-05-27 02:23:18

标签: r dplyr conditional

在R数据帧中,我想在其他字符列和查找字符向量的条件下改变字符列。

例如:

Mydata %>%
mutate(CharColumn1 = case_when(
Charcolumn2 %in% Charvector & Charcolumn3 == "character1" ~ "character2",
Charcolumn2 %in% Charvector & Charcolumn3 == "character2" ~ "character1",
TRUE ~ Charcolumn3))

我使用了上面的示例,但没有用。事实上它根本没有改变。我也尝试过Ifelse,但是将值变为TRUE或FALSE而不是“character1”或“character2”。最后但并非最不重要的是我试着这样做:

Mydata %>%
charcolumn1[charcolumn2 %in% charvector & charcolumn3 == "character1"] <- "character2" %>%
charcolumn1[charcolumn2 %in% charvector & charcolumn3 == "character2"] <- "character1" 

但是这个方法给了我一个错误:“赋值目标扩展到非语言对象”

有人可以帮助我吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

如果您将条件语句包装在()

中,则代码将按原样运行
Mydata %>%
  mutate(
    CharColumn1 = case_when(
      (Charcolumn2 %in% Charvector) & (Charcolumn3 == "character1") ~ "character2",
      (Charcolumn2 %in% Charvector) & (Charcolumn3 == "character2") ~ "character1",
      TRUE ~ Charcolumn3))

输出:

   Charcolumn2 Charcolumn3 CharColumn1
1            d  character1  character1
2            e  character3  character3
3            d  character1  character1
4            a  character1  character2
5            a  character3  character3
6            c  character3  character3
7            b  character2  character1
8            c  character3  character3
9            b  character1  character2
10           a  character2  character1

数据:

library(tidyverse)
set.seed(40)
N <- 10
Charvector <- c("a", "b")
Mydata <- data.frame(Charcolumn2 = sample(letters[1:5], replace=TRUE, size=N), 
                     Charcolumn3 = sample(paste0("character",1:3), replace=TRUE, size=N),
                     stringsAsFactors = FALSE)