So say I have a data frame like this:
data.frame(x = c(1,1,1,3,3,3),y = c(12,32,43,16,32,65))
and I want to transform it into a data frame like this:
data.frame(x = c(1, 3), y_1 = c(12,16), y_2 =c(32, 32),y_3= c(43, 65))
basically spreading the y values for each unique x value. I've tried to do this using tidyr but can't quite see how it would work. Any ideas?
Thanks.
Here's a data.table
solution:
library(data.table)
dat = as.data.table(df) # or setDT to convert in place
dat[, obs := paste0('y_', 1:.N), by=x]
dcast(dat, x ~ obs, value.var="y")
# x y_1 y_2 y_3
#1: 1 12 32 43
#2: 3 16 32 65
This will work even if the number of rows is not the same for all x
.
We can use aggregate
, and then cSplit
from splitstackshape
package to coerce to data frame,
library(splitstackshape)
df1 <- aggregate(y ~ x, df, paste, collapse = ',')
df1 <- cSplit(df1, 'y', ',', direction = 'wide')
# x y_1 y_2 y_3
#1: 1 12 32 43
#2: 3 16 32 65
The answer given by Sotos using aggregate
is particularly elegant, but the following approach using reshape
might also be instructive:
df <- data.frame(x = c(1,1,1,3,3,3),y = c(12,32,43,16,32,65))
df[,"time"] <- rep(1:3, 2)
wide_df <- reshape(df, direction="wide", timevar="time", idvar="x")
One option with dplyr/tidyr
library(dplyr)
library(tidyr)
df1 %>%
group_by(x) %>%
mutate(n = paste("y", row_number(), sep="_")) %>%
spread(n,y)
# x y_1 y_2 y_3
# (dbl) (dbl) (dbl) (dbl)
#1 1 12 32 43
#2 3 16 32 65
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.