【问题标题】:convert list with vectors of different length into data frame将具有不同长度向量的列表转换为数据框
【发布时间】:2017-10-31 14:59:16
【问题描述】:

我正在尝试将包含多个不同长度(类型因子)的向量的列表转换为具有与列表中元素相同的行数且只有一列的数据框。

例子:

ex.list <- (list(c("Tom", "Ron", "Joe"), c("Ron", "Joe"), c("Tom")))
ex.list <- lapply(ex.list, function(x) as.factor(x))

期望的输出是:

ex.list
        col1
    #1 Tom, Ron, Joe
    #2 Ron, Joe
    #3 Tom

当我打电话给str(ex.list$col1) 我想得到:

Factor w/3 levels: "Tom, Ron, Joe"

在 3 行 3 列的数据框中转换 ex.list 没有问题,但这不是我想要的。

这里最好的方法是什么? 我应该unlist 并以某种方式将向量排序到这个 3 行 1 列数据帧中吗?有没有方便的功能来做到这一点?

【问题讨论】:

  • 我不明白你想要的输出。如果它只是一个包含一列的数据框,那么第一行是否应该包含 "Tom, Ron, Joe" 作为字符串?因为这与它也是您想要的水平的一个因素相冲突。
  • stack(setNames(ex.list,seq_along(ex.list))) ?

标签: r list dataframe


【解决方案1】:
df =  data.frame(col1 = unlist(lapply(ex.list, paste, collapse = ", ")))
> df
           col1
1 Tom, Ron, Joe
2      Ron, Joe
3           Tom

要获得唯一名称,您必须运行类似这样的操作

> unique(unlist(strsplit(as.character(df[ , 1]), ", ")))
[1] "Tom" "Ron" "Joe"

您将无法按照您想要的 data.frame 设置方式查看因子的水平。

【讨论】:

  • 这正是我所需要的!谢谢。
【解决方案2】:

您可以将列表列与tidyr::nest 和tidyr::unnest 一起使用:

library(tidyverse)
df <- data.frame(id=seq_along(ex.list), col1 = unlist(lapply(ex.list, paste, collapse = ","))) %>%
  mutate(col1 = stringr::str_split(col1, ",")) %>%
  unnest %>% 
  mutate(col1=as.factor(col1)) %>% 
  nest(col1)

str(df)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   3 obs. of  2 variables:
 $ id  : int  1 2 3
 $ data:List of 3
  ..$ :Classes ‘tbl_df’, ‘tbl’ and 'data.frame':    3 obs. of  1 variable:
  .. ..$ col1: Factor w/ 3 levels "Joe","Ron","Tom": 3 2 1
  ..$ :Classes ‘tbl_df’, ‘tbl’ and 'data.frame':    2 obs. of  1 variable:
  .. ..$ col1: Factor w/ 3 levels "Joe","Ron","Tom": 2 1
  ..$ :Classes ‘tbl_df’, ‘tbl’ and 'data.frame':    1 obs. of  1 variable:
  .. ..$ col1: Factor w/ 3 levels "Joe","Ron","Tom": 3

【讨论】:

  • 或者只是data.frame(id=seq_along(ex.list), data=I(ex.list))
  • 感谢@thelatemail,这要简单得多。但它似乎仍然没有达到 OP 的期望
猜你喜欢
  • 1970-01-01
  • 2013-04-07
  • 2020-02-13
  • 1970-01-01
  • 2020-02-18
  • 2023-03-22
  • 1970-01-01
  • 2018-08-07
  • 2015-03-11
相关资源
最近更新 更多