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

问题描述 投票:1回答:1
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")))

帮助将不胜感激。

r tidyverse
1个回答
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")
© www.soinside.com 2019 - 2024. All rights reserved.