本文介绍了将列表转换为一行data.frame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的列表:
arg0 <- list(code = "a", n = rep(10, 3))
列表中的对象数是可变的.列表中的对象是矢量-只有一维对象.
The number of objects in a list is variable. The objects of the list are vectors -- only one dimensional objects.
我想制作一个将列表转换为一行的data.frame的过程,如下所示:
I want to make a procedure to convert the list to a one row data.frame like this:
> data.frame(code = "a", n.1 = 10, n.2 = 10, n.3 = 10)
code n.1 n.2 n.3
1 a 10 10 10
我目前有此解决方案:
a <- stack(arg0)
b <- data.frame(t(a[,1]))
names(b) <- a[,2]
b <- data.frame(b)
b
几乎是我想要达到的结果:
Where b
is almost the result I want to achieve:
> b
code n n.1 n.2
1 a 10 10 10
两个问题:
- 是否有更优雅的方法来达到目的?
- 您是否知道如何获取重复的姓氏(如
c(n.1,n.2, n.3)
)的编号?
- Is there more elegant way to achieve the result?
- Do you have any idea how to get the numbering of the duplicate colnames like
c(n.1,n.2, n.3)
?
推荐答案
如果要保留列表对象的不同数据类型,可以使用以下命令:
If you want to keep the different data types of the list's objects, the following command can be used:
data.frame(lapply(arg0, function(x) t(data.frame(x))))
输出:
code n.1 n.2 n.3
x a 10 10 10
第二到四列中的值仍然是数字.
The values in columns two to four are still numeric.
这篇关于将列表转换为一行data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!