Reputation: 43
I have a data frame which looks like this:
d <- c("a", "b", "c", "a", "b", "c", "a", "b", "c")
par <- c("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9")
df1 <- as.data.frame(cbind(id, par))
I would like it to look like this:
a <- c("a1", "a4", "a7")
b <- c("a2", "a5", "a8")
c <- c("a3", "a6", "a7")
df2 <- data.frame(rbind(a, b, c))
Upvotes: 1
Views: 2372
Reputation: 886948
You could do this with unstack
as.data.frame(t(unstack(df1,par~id)))
# V1 V2 V3
#a a1 a4 a7
#b a2 a5 a8
#c a3 a6 a9
Or using dcast
after creating a sequence column for the 'id' group.
library(data.table)#v1.9.5
dcast(setDT(df1)[, ind:= 1:.N, id], id~ind, value.var='par')
Upvotes: 1
Reputation: 43
I have solved this as below, seems too messy though
id <- c("a", "b", "c", "a", "b", "c", "a", "b", "c")
par <- c("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9")
df1 <- as.data.frame(cbind(id, par))
ids <- levels(df1$id)
newdf <- list()
for ( i in 1:length(ids)){
tempdf <- df1[df1$id == ids[i],]
id <- tempdf[1,1]
parcels <- tempdf[,2]
row <- cbind(as.character(id), t(as.character(parcels)))
tempdf <- as.data.frame(row)
newdf[[i]] <- tempdf
}
df3 <- do.call(rbind.fill, newdf)
Upvotes: 0