使用tidyr的gather_ [英] Using tidyr's gather_

查看:97
本文介绍了使用tidyr的gather_的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能很简单:

我想使用 tidyr data.frame 上> gather _ :

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))

首先,使用 gather

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

给我想要的结果。

但是,尝试像这样与 gather _ 匹配:

However, trying to match that with gather_ like this:

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

不给我 gather 的用法是什么。

任何想法吗?

推荐答案

我认为你想要:

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
...

由于您正在收集除 id 以外的所有列。就是说,如果您只是想用字符向量指定,仍然可以选择 gather (并且@Maurits Evers指出,不建议使用带下划线的版本) :

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
...

这篇关于使用tidyr的gather_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆