2016-11-22 54 views
5

我需要gather_在數據幀的所有列上,除了一個。例如:我怎樣才能收集所有專欄,而不是一個專欄?

# I want to generate a dataframe whose column names are the letters of the alphabet. If you know of a simpler way, let me know! 
foo <- as.data.frame(matrix(runif(100), 10, 10)) 
colnames(foo) <- letters[1:10] 

現在,假設我要收集所有列,除了e列。這是行不通的:

mycol <- "e" 
foo_melt <- gather_(foo, key = "variable", value = "value", -mycol) 
#Error in -mycol : invalid argument to unary operator 

這將:如果你問我

column_list <- colnames(foo) 
column_list <- column_list[column_list != mycol] 
foo_melt <- gather_(foo, key = "variable", value = "value", column_list) 

看起來頗爲費解。沒有更簡單的方法嗎?

+2

一種選擇是'setdiff'即'gather_(FOO,鍵= 「可變」,值= 「值」,setdiff(名稱(富),mycol))' – akrun

回答

9

一種選擇是one_ofgather

res1 <- gather(foo, key = "variable", value = "value", -one_of(mycol)) 

,如果我們需要gather_,然後setdiff可用於

res2 <- gather_(foo, key = "variable", value = "value", setdiff(names(foo), mycol)) 

identical(res1, res2) 
#[1] TRUE 
dim(res1) 
#[1] 90 3 

head(res1, 3) 
#   e variable  value 
#1 0.8484310  a 0.2730847 
#2 0.0501665  a 0.8129584 
#3 0.6689233  a 0.5457884 
+1

優秀!我現在甚至不需要'gather_' - 我使用它,因爲重塑的變量是動態的,但是'one_of'我仍然可以使用'gather'。 – DeltaIV

1

試試這個:

foo_melt <- gather_(foo, key = "variable", value = "value",names(foo)[-5]) 

這會給你一切除第5個(「e」)以外的列。

> head(foo_melt) 
      e variable  value 
1 0.6359394  a 0.9567835 
2 0.1558724  a 0.7778139 
3 0.1418696  a 0.2132809 
4 0.7184244  a 0.4539194 
5 0.4487064  a 0.1049392 
6 0.5963304  a 0.8692680