简体   繁体   中英

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 .

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM