Reputation: 15
While practicing the gather function with the examples in gather document. I found the result is not automatically named as stock and price I gave in the gather function argument. Thus I'll have to use mutate or rename function after that. Is that per design or how can I get the name there with gather function? I also checked the question previously asked, tidyr gather: simultaneously gather and rename key?, however, I tried the answer provided by Steven, but it will show:
Error in match.names(clabs, names(xi)) :
names do not match previous names" when I do gather.
For rename
function, do we have to specify every name even though I only want to rename certain columns?
It shows
Error: All arguments to rename must be named.
So looks like I need to assign to the same name itself if I don't want to change some column name?
I am using Mac with 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)
similar questions in another thread,Can't change the column names outputted by "gather" to be anything other than the default names
I tried to detach plyr
but still not working.
Upvotes: 0
Views: 812
Reputation: 1622
I do get the right result of stock and price names with
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
If what you want to rename is X, Y and/or Z, then you can do
# Rename before gathering
stocks_long2 <- stocks %>%
rename(X1=X, Y1=Y, Z1=Z) %>%
gather(stock, price, -time)
stocks_long2
Hope this helps
EDIT:
If you don't want the time
variable, you can do something like
stocks_long3 <- stocks %>%
gather(stock, price, -time) %>%
select(-time)
stocks_long3
Upvotes: 0