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

How to coerce space-delimited strings to a column of numeric vectors?

This seems simple, but none of the approaches I’ve tried have worked.

I have a tibble b2d with the following structure:

A tibble: 5 × 2
   bin    day                                                                                   
   <chr>  <chr>                                                                                 
 1 Bin_1  2 5 6 7 8 9 10 11 12 13 14 15 19 21 26 27 28 29 30                                    
 2 Bin_2  1 2 4 6 13 14 15 16 17 18 20 21 22 23 24 25 26 27 28 29 30 31                         
 3 Bin_3  2 3 4 5 7 8 13 14 18 26                                                               
 4 Bin_4  19                                                                                    
 5 Bin_5  1 8 20

day is a column of character strings comprised of integers and spaces. I want to convert each string to a numeric vector, such that day can be searched with the %in% operator (e.g. 1 %in% b2d$day[[1]] returns FALSE; 25 %in% b2d$day[[2]] returns TRUE).

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

My desired output:

A tibble: 5 × 2
   bin    day      
   <chr>  <list>   
 1 Bin_1  <num [19]>
 2 Bin_2  <num [22]>
 3 Bin_3  <num [10]>
 4 Bin_4  <num [1]>
 5 Bin_5  <num [3]>

What I’ve tried, without luck:

https://stackoverflow.com/a/44521160/7976890

b2d %>% mutate(day = as.numeric(unlist(strsplit(day, " "))))

https://stackoverflow.com/a/26342774/7976890

b2d %>% mutate(day = as.numeric(strsplit(day, split = " ", fixed = TRUE)[[1]]))

>Solution :

When it is unlisted, it will unlist the whole list. We may need to loop over the list with map and convert to numeric. map returns a list

library(dplyr)
library(purrr)
b2d %>%
   mutate(day = map(strsplit(day, " "), as.numeric))
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