构建data.frame以设置名称?

时间:2012-08-29 23:36:58

标签: r

我可以使用do.call函数将list转换为data.frame:

z=list(c(1:3),c(5:7),c(7:9))
x=as.data.frame(do.call(rbind,z))
names(x)=c("one","two","three")
x

##   one two three
## 1   1   2     3
## 2   5   6     7
## 3   7   8     9

我想让它更简洁,将两个陈述合并为一个陈述,可以吗?

x=as.data.frame(do.call(rbind,z))  
names(x)=c("one","two","three")

2 个答案:

答案 0 :(得分:7)

setNames就是你想要的。它位于stats包中,应加载R

setNames(as.data.frame(do.call(rbind,z)), c('a','b','c'))

##   a b c
## 1 1 2 3
## 2 5 6 7
## 3 7 8 9

答案 1 :(得分:3)

另一种选择是structure()函数,这是基础的,更通用的是:

structure(as.data.frame(do.call(rbind,z)), names=c('a','b','c'))
相关问题