[英]Create a column based on characters from another column R
I am looking to create a new column based off of labels present in another column. 我希望根据另一列中存在的标签创建一个新列。 For a simple example suppose I have the following 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
What I need to do is create a new column based on the middle character in the "label". 我需要做的是基于“标签”中的中间字符创建一个新列。 I have managed to do this with the code below, but I feel there must be a more elegant way of doing this which is currently beyond me.
我已经用下面的代码做到了这一点,但是我觉得必须有一种更优雅的方式来做到这一点,而这是我目前无法做到的。
> 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
Thanks in advance. 提前致谢。
You can use strsplit
. 您可以使用
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
Here an easy solution using base R code: 这是一个使用基本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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.