将命名向量转换为数据框 [英] Convert named vector to dataframe
本文介绍了将命名向量转换为数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个命名向量:
x <- 1:5
names(x) <- c('0 15', '1 15', '2 15', '0 16', '1 16')
将 x
转换为此数据帧的最佳方法是什么:
What is the best way to convert x
to this dataframe:
xDF <- data.frame(V1 = c(0, 1, 2, 0, 1), V2 = c(15, 15, 15, 16, 16), V3 = 1:5)
推荐答案
这是一种非常直接的方法: / p>
Here's a very direct approach:
cbind(read.table(text = names(x)), x)
V1 V2 x
0 15 0 15 1
1 15 1 15 2
2 15 2 15 3
0 16 0 16 4
1 16 1 16 5
在这种情况下, read.table
将自动处理拆分名称(x)
组件(默认情况下,按空格,但是如果需要,可以指定其他字符)。
In this case, read.table
will automatically take care of splitting your names(x)
component (by default, by space, but other characters could be specified if necessary).
您还可以直接在 cbind
中设置 x
的名称:
You can also set the name for x
directly in cbind
:
cbind(read.table(text = names(x)), V3 = x)
更直接的方法是使用来自我的 splitstackshape软件包的 cSplit
,例如:
library(splitstackshape)
cSplit(stack(x), "ind", " ")
这篇关于将命名向量转换为数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文