2016-11-22 20 views
5

Potrzebuję do gather_ we wszystkich kolumnach ramki danych, z wyjątkiem jednej. Przykład:Jak mogę zebrać_ we wszystkich kolumnach oprócz jednego?

# 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] 

Teraz załóżmy, że chcę zbierać na wszystkich kolumnach oprócz kolumny e. To nie będzie działać:

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

to wola:

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

Wygląda dość zagmatwana jeśli o mnie chodzi. Czy nie ma prostszego sposobu?

+2

Jedną z opcji jest 'setdiff' tj' gather_ (foo, key = "zmienny", value = "wartość", setdiff (nazwy (foo), Mycol)) ' – akrun

Odpowiedz

9

Jedną z opcji jest one_of z gather

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

a jeśli musimy gather_, następnie setdiff można stosować

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

Fantastic! Nie potrzebuję nawet 'gather_' teraz - użyłem go, ponieważ zmienna, na której zmieni się kształt, jest dynamiczna, ale z' one_of' mogę nadal używać 'gather'. – DeltaIV

1

Spróbuj tego:

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

To daje wszystkie kolumny z wyjątkiem piątego ("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 
Powiązane problemy