到/来自 Data.Frame 的命名列表 [英] Named List To/From Data.Frame
问题描述
我正在寻找一种在以下格式列表之间来回切换的快速方法:
I'm looking for a quick way to get back and forth between a list of the following format:
$`a`
[1] 1 2 3
$`b`
[1] 4 5 6
到/来自以下格式的 data.frame:
to/from a data.frame of the following format:
name x
1 a 1
2 a 2
3 a 3
4 b 4
5 b 5
6 b 6
(在这种情况下,不要真正关心列的名称是什么.)
(Don't really care what the names of the columns are, in this case.)
这是上面使用的 R 格式的数据框:
Here's the data frame used above in R-format:
df <- data.frame(name=c(rep("a",3),rep("b",3)), x=c(1:3,4:6))
同样,我正在寻找两个单独的操作:一个将上述 data.frame 转换为列表,另一个将其转换回 data.frame.
Again, I'm looking for two separate operations: one to convert the above data.frame to a list, and another to convert it back to a data.frame.
推荐答案
Use stack
and unstack
in base R:
Use stack
and unstack
in base R:
x <- data.frame(a=1:3, b=4:6)
x
a b
1 1 4
2 2 5
3 3 6
使用 stack
从宽到高,即将向量堆叠在一起.
Use stack
to from wide to tall, i.e. stack the vectors on top of one another.
y <- stack(x)
y
values ind
1 1 a
2 2 a
3 3 a
4 4 b
5 5 b
6 6 b
使用 unstack
来做相反的事情.
Use unstack
to do the reverse.
unstack(y)
a b
1 1 4
2 2 5
3 3 6
<小时>
如果您的数据结构比您描述的更复杂,stack
和 unstack
可能不再适合.在这种情况下,您必须在基础 R 中使用 reshape
,或在包 reshape2
中使用 melt
和 dcast
.
If your data structure is more complicated than you described, stack
and unstack
may no longer be suitable. In that case you'll have to use reshape
in base R, or melt
and dcast
in package reshape2
.
这篇关于到/来自 Data.Frame 的命名列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!