[英]Why are my data.frame columns lists?
I have a data.frame
我有一个
data.frame
'data.frame': 4 obs. of 2 variables:
$ name:List of 4
..$ : chr "a"
..$ : chr "b"
..$ : chr "c"
..$ : chr "d"
$ tvd :List of 4
..$ : num 0.149
..$ : num 0.188
..$ : num 0.161
..$ : num 0.187
structure(list(name = list("a", "b", "c",
"d"), tvd = list(0.148831029536996, 0.187699857380692,
0.161428147003292, 0.18652668961466)), .Names = c("name",
"tvd"), row.names = c(NA, -4L), class = "data.frame")
It appears that as.data.frame(lapply(z,unlist))
converts it to the usual 似乎
as.data.frame(lapply(z,unlist))
将其转换为通常的
'data.frame': 4 obs. of 2 variables:
$ name: Factor w/ 4 levels "a",..: 4 1 2 3
$ tvd : num 0.149 0.188 0.161 0.187
However, I wonder if I could do better. 但是,我想知道我能不能做得更好。 I create my ugly data frame like this:
我像这样创建我丑陋的数据框:
as.data.frame(do.call(rbind,lapply(my.list, function (m)
list(name = ...,
tvd = ...))))
I wonder if it is possible to modify this expressing so that it would produce the normal data table. 我想知道是否有可能修改这种表达方式,以便产生正常的数据表。
It looks like you're just trying to tear down your original data then re-assemble it? 看起来您只是想要拆除原始数据然后重新组装它? If so, here are a few cool things to look at.
如果是这样,这里有一些很酷的事情要看。 Assume
df
is your data. 假设
df
是你的数据。
A data.frame
is just a list in disguise. data.frame
只是伪装的列表。 To see this, compare df[[1]]
to df$name
in your data. 要查看此信息,请在数据中将
df[[1]]
与df$name
进行比较。 [[
is used for list indexing, as well as $
. [[
用于列表索引,以及$
。 So we are actually viewing a list item when we use df$name
on a data frame. 因此,当我们在数据框上使用
df$name
时,我们实际上正在查看列表项。
> is.data.frame(df) # df is a data frame
# [1] TRUE
> is.list(df) # and it's also a list
# [1] TRUE
> x <- as.list(df) # as.list() can be more useful than unlist() sometimes
# take a look at x here, it's a bit long
> (y <- do.call(cbind, x)) # reassemble to matrix form
# name tvd
# [1,] "a" 0.148831
# [2,] "b" 0.1876999
# [3,] "c" 0.1614281
# [4,] "d" 0.1865267
> as.data.frame(y) # back to df
# name tvd
# 1 a 0.148831
# 2 b 0.1876999
# 3 c 0.1614281
# 4 d 0.1865267
I recommend doing 我建议做
do.call(rbind,lapply(my.list, function (m)
data.frame(name = ...,
tvd = ...)))
rather than trying to convert a list of lists into a data.frame 而不是尝试将列表列表转换为data.frame
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.