Reputation: 71
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.
Upvotes: 1
Views: 2118
Reputation: 5017
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
Upvotes: 4
Reputation: 5893
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
Upvotes: 3