R:如何从数据框中提取列表?

时间:2017-06-29 18:00:18

标签: r dplyr

考虑这个简单的例子

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

我需要提取col_weird中的值。我怎样才能做到这一点?我看到如何在Python中执行此操作,但不在R中。预期输出为:

> 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

5 个答案:

答案 0 :(得分:2)

weird_df <- data_frame(col1 = c('hello', 'world'),
                   col_weird = list(list(12,23), list(23,24)))

library(dplyr)
weird_df %>%
  dplyr::mutate(tic = unlist(magrittr::extract2(col_weird, 1)),
                toc = unlist(magrittr::extract2(col_weird, 2)),
                col_weird = NULL)

使用上次更改:请注意,现在col_weird包含list(NA, NA)

weird_df <- data_frame(col1 = c('hello', 'world', 'again'),
                  col_weird = list(list(12,23), list(23,24), list(NA, NA)))

library(dplyr)
weird_df %>%
 dplyr::mutate(col_weird = matrix(col_weird),
 tic = sapply(col_weird, function(x) magrittr::extract2(x, 1)),
 toc = sapply(col_weird, function(x) magrittr::extract2(x, 2)),
 col_weird = NULL)

答案 1 :(得分:2)

由于I()

,您可以使用基本R执行此操作
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

答案 2 :(得分:2)

以下是purrr/tidyverse/reshape2的一个选项。我们unlist&#39; col_weird&#39;在map内,要将输出设为list,请将list的名称设置为&#39; col1&#39;,melt为&#39; long&#39 ;格式,按&#39; L1&#39;分组,创建一个&#39;&#39;列和spread后面的广告&#39;

library(tidyverse)
library(reshape2)
weird_df$col_weird %>%
     map(unlist) %>% 
     setNames(., weird_df$col1) %>%
     melt %>% 
     group_by(L1) %>%
     mutate(rn = c('tic', 'toc')[row_number()]) %>%
     spread(rn, value) %>%
     left_join(weird_df[-2], ., by = c(col1 = "L1"))

答案 3 :(得分:2)

好吧,我想出了一个简单的

> weird_df %>% 
+   rowwise() %>%
+   mutate(tic = col_weird[[1]],
+          tac = ifelse(length(col_weird) == 2, col_weird[[2]], NA)) %>% 
+   select(-col_weird) %>% ungroup()
# A tibble: 3 x 3
   col1   tic   tac
  <chr> <dbl> <dbl>
1 hello    12    23
2 world    23    24
3 again    NA    NA

答案 4 :(得分:2)

如果将列表列折叠为字符串,则可以使用 tidyr 中的separate。我使用 purrr 中的map循环遍历列表列,并使用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

您实际上可以在没有separate部分的情况下直接使用toString但最终会使用&#34; list&#34;作为其中一个价值观。

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

这导致我tidyr::extract,它使用正确的正则表达式工作正常。但是,如果列表列更复杂,那么写出正则表达式可能会很麻烦。

weird_df %>%
     extract(col_weird, into = c("tic", "toc"), regex = "([[:digit:]]+), ([[:digit:]]+)", convert = TRUE)