根据另一列R中的字符创建一列

时间:2018-04-27 08:34:08

标签: r string dataframe

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

> 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

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以使用strsplit

df %>%
  mutate(newCol = map_chr(label, ~unlist(strsplit(., ""))[2])) %>%
  mutate(newCol = case_when(newCol == "F" ~ "fairies",
                            newCol == "O" ~ "ogres"))

  label somevalue  newCol
1   AF1         1 fairies
2   AF2         2 fairies
3   AO1         3   ogres
4   AO1         4   ogres

答案 1 :(得分:1)

这是一个使用基本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