Home > Blockchain >  How do I create a new column and fill it with the content of another column with R's tidyverse?
How do I create a new column and fill it with the content of another column with R's tidyverse?

Time:10-01

Current data:

name age sex

Steve 12_pink M
Darrel 14_green M
Barney 19_blue M
Lola 24_cyan F

I am trying to fill the 'colors' column with the color that is in the 'age' column so it looks like the following.

Desired data:

name age sex color

Steve 12 M pink

Darrel 14 M green

Barney 19 M blue

Lola 24 F cyan

Anyways to do so? I was thinking of using mutate() to create the 'color' column but wasn't sure how to fill it. Thanks!

CodePudding user response:

tidyr::separate can help here:

library(tidyr)

df <- data.frame(
  name = c("Steve", "Darrel", "Barney", "Lola"),
  age = c("12_pink", "14_green", "19_blue", "24_cyan"),
  sex = c("M", "M", "M", "F")
)

df |> separate(age, into = c("color", "age"))

#>     name color   age sex
#> 1  Steve    12  pink   M
#> 2 Darrel    14 green   M
#> 3 Barney    19  blue   M
#> 4   Lola    24  cyan   F
  • Related