From long to wide form without id.var?

↘锁芯ラ 提交于 2019-12-02 01:20:54

I'm pretty sure this has been answered before. Anyway, unstack is convenient in this particular case with equal group size:

unstack(dat1, form = value ~ id)
#   A B
# 1 1 5
# 2 2 6
# 3 3 7
# 4 4 8
Pafnucy

Solution below works when there are different numbers of As and Bs. For equal counts, unstack works great and with less code (Henrik's answer).

# create more general data (unbalanced 'id')
each <- c(4,2,3)
dat1 = data.frame(
    id = unlist(mapply(rep, x = LETTERS[1:length(each)], each = each)),
    value = 1:sum(each),
    row.names = 1:sum(each) # to reproduce original row.names
)

tab <- table(dat1$id)
dat1$timevar <- unlist(sapply(tab, seq))
library(reshape2)
dcast(dat1, timevar ~ id )[-1]

initial data:

id value
1  A     1
2  A     2
3  A     3
4  A     4
5  B     5
6  B     6
7  C     7
8  C     8
9  C     9

result:

  A  B  C
1 1  5  7
2 2  6  8
3 3 NA  9
4 4 NA NA

Here's a base R approach to consider. It uses the lengths function, which I believe was introduced in R 3.2.

x <- split(dat1$value, dat1$id)
as.data.frame(lapply(x, function(y) `length<-`(y, max(lengths(x)))))
#   A  B  C
# 1 1  5  7
# 2 2  6  8
# 3 3 NA  9
# 4 4 NA NA
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!