I have the following dataframe. I applied the str_split() function to YEARS.
library(dplyr)
library(stringr)
YEARS <- c("2020/2021", "2021/2022", "2022/2023")
VALUE <- c(10,5,3)
x <- data.frame(YEARS, VALUE) %>%
mutate(YEARS=str_split(YEARS, "/"))
I want to keep only the first element of the list for every YEARS, using dplyr if possible.
I tried this
x %>% mutate(YEARS=YEARS[[1]][1])
but it didn’t work and just changed every value to 2020 :
| YEARS | VALUE |
|---|---|
| 2020 | 10 |
| 2020 | 5 |
| 2020 | 3 |
I also tried with purrr but same result.
Does anyone kows why it’s not working properly and how to fix it ?
>Solution :
Try this:
library(dplyr)
library(stringr)
library(purrr)
YEARS <- c("2020/2021", "2021/2022", "2022/2023")
VALUE <- c(10, 5, 3)
x <- data.frame(YEARS, VALUE) %>%
mutate(YEARS = map(YEARS, ~ str_split(.x, "/")[[1]][1]))