我有一个命名元素列表(testlist),其中一些名称是重复的
$x
[1] "one"
$x
[1] "two"
$y
[1] "three"
$y
[1] "four"
Run Code Online (Sandbox Code Playgroud)
我试图最终得到一个数据表,它将元素与通用名称组合到同一列中.
x y
1: one three
2: two four
Run Code Online (Sandbox Code Playgroud)
我试过了
testdf <- do.call(cbind, lapply(testlist, data.table))
Run Code Online (Sandbox Code Playgroud)
但最终只有:
x.V1 x.V1 y.V1 y.V1
1: one two three four
Run Code Online (Sandbox Code Playgroud)
有什么建议?感谢帮助!
与上一个问题相关的是,有没有办法将一些命名元素列表转换成一个数据表,其中NA值实际按照它们出现在列表中的顺序显示在数据表中?
例如:列表
testlist <- list("Blue", "405", "Truck", "400", "Car", "White", "500", "Truck")
testnames <- c("Color", "HP", "Type", "HP", "Type", "Color", "HP", "Type")
names(testlist) <- testnames
$Color
[1] "Blue"
$HP
[1] "405"
$Type
[1] "Truck"
$HP
[1] "400"
$Type
[1] "Car"
$Color
[1] "White"
$HP
[1] "500"
$Type
[1] "Truck"
Run Code Online (Sandbox Code Playgroud)
可以使用以下方法更改为数据表:
dcast(setDT(melt(testlist))[, N:=1:.N, L1], N~L1, value.var='value')
Run Code Online (Sandbox Code Playgroud)
但输出是这样的:
N Color HP Type
1 1 Blue 405 Truck
2 2 White 400 Car
3 3 <NA> 500 Truck
Run Code Online (Sandbox Code Playgroud)
当我想要:
N Color …Run Code Online (Sandbox Code Playgroud)