Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to extract a list from a dataframe?

Tags:

r

dplyr

Consider this simple example

> weird_df <- data_frame(col1 =c('hello', 'world', 'again'),
+                       col_weird = list(list(12,23), list(23,24), NA))
> 
> weird_df
# A tibble: 3 x 2
   col1  col_weird
  <chr>     <list>
1 hello <list [2]>
2 world <list [2]>
3 again  <lgl [1]>

I need to extract the values in the col_weird. How can I do that? I see how to do that in Python but not in R. Expected output is:

> good_df
# A tibble: 3 x 3
   col1   tic   toc
  <chr> <dbl> <dbl>
1 hello    12    23
2 world    23    24
3 again    NA    NA
like image 953
ℕʘʘḆḽḘ Avatar asked Jun 29 '17 18:06

ℕʘʘḆḽḘ


2 Answers

If you collapse the list column into a string you can use separate from tidyr. I used map from purrr to loop through the list column and create a string with toString.

library(tidyr)
library(purrr)

weird_df %>%
     mutate(col_weird = map(col_weird, toString ) ) %>%
     separate(col_weird, into = c("tic", "toc"), convert = TRUE)

# A tibble: 3 x 3
   col1   tic   toc
* <chr> <int> <int>
1 hello    12    23
2 world    23    24
3 again    NA    NA

You can actually use separate directly without the toString part but you end up with "list" as one of the values.

weird_df %>%
     separate(col_weird, into = c("list", "tic", "toc"), convert = TRUE) %>%
     select(-list)

This led me to tidyr::extract, which works fine with the right regular expression. If your list column was more complicated, though, writing out the regular expression might be a pain.

weird_df %>%
     extract(col_weird, into = c("tic", "toc"), regex = "([[:digit:]]+), ([[:digit:]]+)", convert = TRUE)
like image 71
aosmith Avatar answered Nov 15 '22 10:11

aosmith


You can do this with basic R, thanks to I():

weird_df <- data.frame(col1 =c('hello', 'world'), 
   col_weird = I(list(list(12,23),list(23,24))))

weird_df
>    col1 col_weird
  1 hello    12, 23
  2 world    23, 24
like image 29
psychOle Avatar answered Nov 15 '22 12:11

psychOle