2016-11-22 2 views
5

データフレームのすべての列で、gather_にする必要があります。例:1つ以外のすべての列でどのように集めることができますか?

# 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(名前(FOO)、mycol)) ' – akrun

答えて

9

1つのオプションは、gather

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

one_ofであり、我々は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 
関連する問題