0

Current data:

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")
)

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.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

1 Answers1

2

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
Kai Aragaki
  • 377
  • 3
  • 13
  • You are such a life saver!!!!! – morningstarsaus Sep 30 '22 at 23:45
  • @morningstarsaus Something that I find helps me is that when I know what I want my data to *look* like, but not how to do it, I look at the tidyr cheat sheet: https://raw.githubusercontent.com/rstudio/cheatsheets/main/tidyr.pdf – Kai Aragaki Sep 30 '22 at 23:46
  • thank you for the tip! if i wanted to manipulate a data column "Age" that has the element "Age13" in it, how could I change it to be just "13"? Not sure how to remove "Age" in an element of the data. Thanks again. – morningstarsaus Sep 30 '22 at 23:55
  • @morningstarsaus For that you'd probably have to do some regex magic. Since there's no 'separation character' (that is, you want to keep everything, where as in the case of `12_pink` you removed the `_`) I would probably do two separate `mutate`s to make a columns for `color` and `age`, and use `str_extract` or `grep` to pull the values out from the original `age` column. btw if the answer helped you, would you mind accepting it? It helps me out. – Kai Aragaki Oct 01 '22 at 00:04
  • Sure how do I do that? – morningstarsaus Oct 01 '22 at 01:02
  • There should be a checkmark right next to the up and down voting arrows! – Kai Aragaki Oct 01 '22 at 01:05