Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 从列表创建数据框_R_List_Dataframe - Fatal编程技术网

R 从列表创建数据框

R 从列表创建数据框,r,list,dataframe,R,List,Dataframe,我的名单如下: yel <- list(c(1,3,5,7,9), c(1,2,6,9), c(2,4,5,6,7,8,9)) 让我们了解一下我是如何得到这个列表的:我有一个数据框架,它有两列,即“id”和“text”。“文本”列是字符列表。我在字符列表中找到了唯一的单词,并创建了一个数据框“yel”,其中第一个列表表示“id”,其中有“text1”,第二个列表表示“id”,其中有“text2”,依此类推。(例如,我的数据集中的“id”是7170325)。

我的名单如下:

yel <- list(c(1,3,5,7,9),
        c(1,2,6,9),
        c(2,4,5,6,7,8,9))

让我们了解一下我是如何得到这个列表的:我有一个数据框架,它有两列,即“id”和“text”。“文本”列是字符列表。我在字符列表中找到了唯一的单词,并创建了一个数据框“yel”,其中第一个列表表示“id”,其中有“text1”,第二个列表表示“id”,其中有“text2”,依此类推。(例如,我的数据集中的“id”是7170325)。提前非常感谢

获取列表中的最大值,即行数。使用%中的
%检查列表中的每个数组,看看数组中是否存在从1到最大值的所有值。这提供了可以转换为数字的逻辑数据

合并@thelatemail的评论

setNames(as.data.frame(lapply(yel, function(x)
                as.numeric(1:max(unlist(yel)) %in% x))), 1:length(yel))
#  1 2 3
#1 1 1 0
#2 0 1 1
#3 1 0 0
#4 0 0 1
#5 1 0 1
#6 0 1 1
#7 1 0 1
#8 0 0 1
#9 1 1 1

制表
在这里可能很方便:

setNames(data.frame(lapply(yel, tabulate)), seq_along(yel) )
#  1 2 3
#1 1 1 0
#2 0 1 1
#3 1 0 0
#4 0 0 1
#5 1 0 1
#6 0 1 1
#7 1 0 1
#8 0 0 1
#9 1 1 1

我们可以使用
mtabulate

library(qdapTools)
t(mtabulate(yel))
#   [,1] [,2] [,3]
#1    1    1    0
#2    0    1    1
#3    1    0    0
#4    0    0    1
#5    1    0    1
#6    0    1    1
#7    1    0    1
#8    0    0    1
#9    1    1    1

除了我的+1-
max_num
之外,还有两个小点可以是
max(unlist(yel))
lappy
,因为第二步可能更有意义,所以您不打算列出-->矩阵-->数据.frame,而是列出-->数据.frame。@thelatemail,谢谢!我编辑了我的答案以包括你的答案suggestion@d.b非常感谢你!来自大师的更多魔法。@Late Mail感谢您的回复。我试图输入数据,但出现以下错误:函数中出错(…,row.names=NULL,check.rows=FALSE,check.names=TRUE,:参数表示不同的行数:此外:警告消息:1:未知列“i”2:未知列“i”类似的替代方法是使用
table
制作一次表格;
table(未列出(yel),代表(1:长度(yel),长度(yel)))
非常感谢!这在我庞大的数据集上非常有效。我们可以更改顺序或行吗?就像在本例中一样,它已排序,但如果我想按特定顺序排序,我可以使用mtabulate吗?@ManishRanjan是的,您可以将列表元素转换为
因子
,并按您想要的顺序指定
级别m使用
sample
t(mtabulate(lapply(yel,factor,levels=sample(1:9)))
library(qdapTools)
t(mtabulate(yel))
#   [,1] [,2] [,3]
#1    1    1    0
#2    0    1    1
#3    1    0    0
#4    0    0    1
#5    1    0    1
#6    0    1    1
#7    1    0    1
#8    0    0    1
#9    1    1    1