2017-05-11 16 views
0

我有一個數據框,我想要重新排序的列。但是,在我的腳本的不同迭代中,列的總數可能會更改。按名稱和列號調用變量data.frame

>Fruit 
Vendor A B C D E ... Apples Oranges 
Otto 4 5 2 5 2 ... 3  4 

Fruit2<-Fruit[c(32,33,2:5)] 

因此,而不是手動調整的代碼(列32和33的變化),我想做到以下幾點:

Fruit2<-Fruit[,c("Apples", "Oranges", 2:5)] 

我試過一對夫婦語法,但它不能得到做我想做的事。我知道,這是一個簡單的語法問題,但我還找不到解決方案。 這個想法是在寫入一個新的數據框時將變量名與矢量混合來引用列。我不想用變量名拼出整個向量,因爲實際上它有30個變量。

+3

'水果[,c(「蘋果」,「橘子」,名稱(水果)[2:5])]'會起作用 –

回答

0

我不知道你的數據是如何存儲在R,所以這是我用:

Fruit <- data.frame("X1" = c("A",4),"X2" = c("B",5),"X3" = c("C",2),"X4"= 
c("D",5),"X5"= c("E",2),"X6" = c("Apples",3),"X7"= 
c("Oranges",4),row.names = c("Vendor","Otto"),stringsAsFactors = FALSE) 

      X1 X2 X3 X4 X5  X6  X7 
    Vendor A B C D E Apples Oranges 
    Otto 4 5 2 5 2  3  4 

然後使用:

indexes <- which(Fruit[1,]%in%c("Apples","Oranges")) 
Fruit2<- Fruit[,c(indexes,2:5)] 

果[1]參考賣方行,並且「%in%」將邏輯向量返回給函數「which」。然後「哪個」返回索引。

這給:

> Fruit2 
       X6  X7 X2 X3 X4 X5 
    Vendor Apples Oranges B C D E 
    Otto  3  4 5 2 5 2 

確保您的數據不會被存儲爲因素,否則將無法正常工作。或者,您可以按照上面的註釋將供應商行更改爲列名稱。

0

答案是,正如我發現的,使用dplyr軟件包。 它非常強大。

上述問題的解決方案是:

Fruit2<-Fruit %>% select(Apples,Oranges,A:E) 

這使得列與列名單的動態選擇,即使列的索引改變。