Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace column value by element of list from same column

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading