首页 > 解决方案 > 根据另一列 R 中的字符创建一列

问题描述

我希望根据另一列中的标签创建一个新列。举个简单的例子,假设我有以下数据框

> df <- data.frame(label = c("AF1", "AF2", "AO1", "AO1"), somevalue = c(1, 2, 3, 4))
> df
  label somevalue
1   AF1         1
2   AF2         2
3   AO1         3
4   AO1         4

我需要做的是根据“标签”中的中间字符创建一个新列。我已经设法用下面的代码做到了这一点,但我觉得必须有一种更优雅的方式来做到这一点,这是目前我所无法做到的。

> df <- df %>% mutate(newCol = NA)
> df$newCol[str_detect(df$label, "F")] <- "fairies"
> df$newCol[str_detect(df$label, "O")] <- "ogres"
> df
  label somevalue  newCol
1   AF1         1 fairies
2   AF2         2 fairies
3   AO1         3   ogres
4   AO1         4   ogres

提前致谢。

标签: rstringdataframe

解决方案


这是使用基本 R 代码的简单解决方案:

df[substr(df$label,2,2)=="F","newCol"]<-"fairies"
df[substr(df$label,2,2)=="O","newCol"]<-"ogres"
df
  label somevalue  newCol
1   AF1         1 fairies
2   AF2         2 fairies
3   AO1         3   ogres
4   AO1         4   ogres

推荐阅读