使用收集文档中的示例练习聚集功能。 我发现结果不会自动命名为我在gather函数参数中给出的股票和价格。因此,之后我将不得不使用mutate或rename函数。 这是每个设计或我如何获得具有收集功能的名称? 我还检查了之前提出的问题tidyr gather: simultaneously gather and rename key?,然而,我尝试了史蒂文提供的答案,但它会显示:
match.names(clabs,names(xi))出错:
名字与以前的名字不符“我收集的时候。
对于rename
函数,我们是否必须指定每个名称,即使我只想重命名某些列?
它显示
错误:必须命名所有要重命名的参数。
因此,如果我不想更改某些列名,我需要分配相同的名称吗?
我正在使用Mac与Rstudio v0.98.1103,tidyr v0.20,dplyr v0.41
library(dplyr)
# From https://stackoverflow.com/questions/1181060
stocks <- data.frame(
time = as.Date('2009-01-01') + 0:9,
X = rnorm(10, 0, 1),
Y = rnorm(10, 0, 2),
Z = rnorm(10, 0, 4)
)
gather(stocks, stock, price, -time)
另一个帖子Can't change the column names outputted by "gather" to be anything other than the default names
中的类似问题我试图分离plyr
,但仍无法正常工作。
答案 0 :(得分:0)
我确实通过
获得了股票和价格名称的正确结果library(tidyr) # You had put dplyr
library(dplyr) # For the pipes %>%
# From http://stackoverflow.com/questions/1181060
stocks <- data.frame(
time = as.Date('2009-01-01') + 0:9,
X = rnorm(10, 0, 1),
Y = rnorm(10, 0, 2),
Z = rnorm(10, 0, 4)
)
stocks_long1 <- stocks %>%
gather(stock, price, -time)
stocks_long1
如果要重命名的是X,Y和/或Z,则可以执行
# Rename before gathering
stocks_long2 <- stocks %>%
rename(X1=X, Y1=Y, Z1=Z) %>%
gather(stock, price, -time)
stocks_long2
希望这有帮助
修改强>
如果您不想要time
变量,可以执行类似
stocks_long3 <- stocks %>%
gather(stock, price, -time) %>%
select(-time)
stocks_long3