Using tidyr's gather_

﹥>﹥吖頭↗ 提交于 2019-12-11 15:35:54

问题


Probably an easy one:

I'd like to use tidyr's gather_ on this data.frame:

set.seed(1)
df <- data.frame(a=rnorm(10),b=rnorm(10),d=rnorm(10),id=paste0("id",1:10))

First, using gather:

df %>% tidyr::gather(key=name,value=val,-id)

Gives me the desired outcome.

However, trying to match that with gather_ like this:

df %>% tidyr::gather_(key_col="name",value_col="val",gather_cols="id")

Doesn't give me what the gather usage does.

Any idea?


回答1:


I think you want:

df %>% tidyr::gather_(key_col="name",value_col="val",gather_cols= c('a', 'b', 'd'))

     id name         val
1   id1    a -0.62645381
2   id2    a  0.18364332
3   id3    a -0.83562861
4   id4    a  1.59528080
5   id5    a  0.32950777
6   id6    a -0.82046838
7   id7    a  0.48742905
8   id8    a  0.73832471
9   id9    a  0.57578135
10 id10    a -0.30538839
...

Since you're gathering all columns except id. That said, if you're just looking to specify with character vectors, gather is still an option (and as @Maurits Evers points out, the underscore-suffixed versions are deprecated) :

> df %>% tidyr::gather(key="name",value="val",-"id")
     id name         val
1   id1    a -0.62645381
2   id2    a  0.18364332
3   id3    a -0.83562861
4   id4    a  1.59528080
5   id5    a  0.32950777
6   id6    a -0.82046838
7   id7    a  0.48742905
8   id8    a  0.73832471
9   id9    a  0.57578135
10 id10    a -0.30538839
...


来源:https://stackoverflow.com/questions/53640769/using-tidyrs-gather

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!