【发布时间】:2015-02-17 09:10:42
【问题描述】:
我有一个由 5 列组成的数据框。我还有一个包含其中一些列名的数组。我想要一个新的数据框,仅包含名称出现在此数组中的列,但与它们在数组中出现的顺序相同。我能够获得列,但顺序不同。请看下面的代码
col1 = c(1,1,1,1,1)
col2 = c(2,2,2,2,2)
col3 = c(3,3,3,3,3)
col4 = c(4,4,4,4,4)
col5 = c(5,5,5,5,5)
df = data.frame(col1,col2,col3,col4,col5)
df
col1 col2 col3 col4 col5
1 1 2 3 4 5
2 1 2 3 4 5
3 1 2 3 4 5
4 1 2 3 4 5
5 1 2 3 4 5
columnsarray = c("col4","col1","col2")
df[which(names(df) %in% columnsarray)]
col1 col2 col4
1 1 2 4
2 1 2 4
3 1 2 4
4 1 2 4
5 1 2 4
如您所见,我提到的列名称为 col4、col1、col2。但是,输出看起来像 col1 col2 col4。
【问题讨论】:
-
只要
df[columnsarray]就可以了 -
@bergant,哇,太棒了。您能否将其添加为答案,以便我接受
标签: r