无法更改“gather"输出的列名不是默认名称 [英] Can't change the column names outputted by "gather" to be anything other than the default names

查看:15
本文介绍了无法更改“gather"输出的列名不是默认名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 tidyr 包中使用 gather,但我无法更改默认名称的输出列名称.例如:

I'm trying to use gather in the tidyr package, but I'm not able to change the outputted column names from the default names. For instance:

df = data.frame(time = 1:100,a = 1:100,b = 101:200)
df.long = df %>% gather("foo","bar",a:b)
colnames(df.long)

给我

[1] "time"     "variable" "value"   

但不应该是 "time" "foo" "bar" 吗?

我可以将foo"和bar"更改为我想要的任何内容,它仍然给我变量"和值"作为我的列名.

I can change "foo" and "bar" to anything I want, and it still gives me "variable" and "value" as my column names.

帮助.我在这里错过了什么?

Help. What am I missing here?

推荐答案

这可能是一个错误.如果你愿意尝试其他的,比如 data.table 的melt(),你可以在下面做:

This could possibly be a bug. If you are willing to try else, like melt() of data.table, you could do below:

# Need to load both data.table and reshape2
# For more information, could check ?data.table
library(reshape2); library(data.table)
setDT(df)
df %>% melt(id.vars = "time", variable.name = "foo", value.name = "bar")

> First 20 rows
    time foo bar
1:    1   a   1
2:    2   a   2
3:    3   a   3
4:    4   a   4
5:    5   a   5
6:    6   a   6
7:    7   a   7
8:    8   a   8
9:    9   a   9
10:   10   a  10
11:    1   b  11
12:    2   b  12
13:    3   b  13
14:    4   b  14
15:    5   b  15
16:    6   b  16
17:    7   b  17
18:    8   b  18
19:    9   b  19
20:   10   b  20

这篇关于无法更改“gather"输出的列名不是默认名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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