有条件地使用Tidyverse基于另一个Dataframe列中的值替换Dataframe列中的值

时间:2017-11-30 05:13:54

标签: r tidyverse

library(tidyverse)  

Column1<-c("Course1","Course1","Course1","Course2","Course2","Course3","Course3","Course3","    Course4","Course4","Course5","Course5")
Column2<-c("Cat","Dog","Snake","Elephant","Beaver","Rabbit","Fish","Bird","Bear","Horse","Raccoon","Skunk")
Df1<-data.frame(Column1,Column2)

使用上面的示例数据,我想根据“Column2”的值有条件地替换/重新编码“Column1”的值。

对于这个简单的例子,如果“Column2”包含“Cat”或“Dog”,则“Column1”值应替换为“Course6”。

到目前为止,我已尝试过以下代码。它不起作用,但我觉得我很接近。我也更喜欢一个整体解决方案。

map2(Df1[2],Df1[1],~if_else(.x =="Cat"|"Dog", replace(.y, "Course6")))

map2(Df1[2],Df1[1],~if_else(.x =="Cat"|"Dog", replace(.y, .x,"Course6")))

帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

不知道我是否帮到你,但也许这适合你:

df1[df1$Column2 == c("Cat", "Dog"), 1] <- "Course6"

创建数据框时,您必须关闭stringsAsFactors或提供完整的因素列表。

修改

多一点tidyverse

df1 %>%
  spread(key = Column2, value = Column1) %>%
  mutate("Dog" = "Course6") %>%
  gather(key = "Column1", value = "Column2")