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

Time:03-31

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

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

CodePudding user response:

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))
  • Related