我有一个如下所示的数据框:
a b
1 x 8
2 x 6
3 y 3
4 y 4
5 z 5
6 z 6
Run Code Online (Sandbox Code Playgroud)
我想把它变成这个:
x y z
1 8 3 5
2 6 4 6
Run Code Online (Sandbox Code Playgroud)
但是打电话
library(tidyr)
df <- data.frame(
a = c("x", "x", "y", "y", "z", "z"),
b = c(8, 6, 3, 4, 5, 6)
)
df %>% spread(a, b)
Run Code Online (Sandbox Code Playgroud)
回报
x y z
1 8 NA NA
2 6 NA NA
3 NA 3 NA
4 NA 4 NA
5 NA NA 5
6 NA NA 6
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
seb*_*n-c 13
虽然我知道你在追求tidyr,base但在这种情况下有一个解决方案:
unstack(df, b~a)
Run Code Online (Sandbox Code Playgroud)
它也快一点:
Unit: microseconds
expr min lq mean median uq max neval
df %>% spread(a, b) 657.699 679.508 717.7725 690.484 724.9795 1648.381 100
unstack(df, b ~ a) 309.891 335.264 349.4812 341.9635 351.6565 639.738 100
Run Code Online (Sandbox Code Playgroud)
我没有包括data.table解决方案,因为我不确定通过引用是否会成为问题microbenchmark.
library(microbenchmark)
library(tidyr)
library(magrittr)
nlevels <- 3
#Ensure that all levels have the same number of elements
nrow <- 1e6 - 1e6 %% nlevels
df <- data.frame(a=sample(rep(c("x", "y", "z"), length.out=nrow)),
b=sample.int(9, nrow, replace=TRUE))
microbenchmark(df %>% spread(a, b), unstack(df, b ~ a), data.frame(split(df$b,df$a)), do.call(cbind,split(df$b,df$a)))
Run Code Online (Sandbox Code Playgroud)
即使在100万,倒塌也更快.值得注意的是,split解决方案也非常快.
Unit: milliseconds
expr min lq mean median uq max neval
df %>% spread(a, b) 366.24426 414.46913 450.78504 453.75258 486.1113 542.03722 100
unstack(df, b ~ a) 47.07663 51.17663 61.24411 53.05315 56.1114 102.71562 100
data.frame(split(df$b, df$a)) 19.44173 19.74379 22.28060 20.18726 22.1372 67.53844 100
do.call(cbind, split(df$b, df$a)) 26.99798 27.41594 31.27944 27.93225 31.2565 79.93624 100
Run Code Online (Sandbox Code Playgroud)
不知何故这样吗?
df <- data.frame(ind = rep(1:min(table(df$a)), length(unique(df$a))), df)
df %>% spread(a, b) %>% select(-ind)
ind x y z
1 1 8 3 5
2 2 6 4 6
Run Code Online (Sandbox Code Playgroud)
你可以做到这一点dcast,并rowid从data.table包,以及:
dat <- dcast(setDT(df), rowid(a) ~ a, value.var = "b")[,a:=NULL]
Run Code Online (Sandbox Code Playgroud)
这使:
Run Code Online (Sandbox Code Playgroud)> dat x y z 1: 8 3 5 2: 6 4 6
旧解决方案:
# create a sequence number by group
setDT(df)[, r:=1:.N, by = a]
# reshape to wide format and remove the sequence variable
dat <- dcast(df, r ~ a, value.var = "b")[,r:=NULL]
Run Code Online (Sandbox Code Playgroud)
这使:
Run Code Online (Sandbox Code Playgroud)> dat x y z 1: 8 3 5 2: 6 4 6
| 归档时间: |
|
| 查看次数: |
1011 次 |
| 最近记录: |