如何使用dplyr
问题描述:
行转换成列我有以下的数据帧(tibble):如何使用dplyr
library(tidyverse)
lines<-"
A,foo,9394981
B,bar,6826405
C,qux,1074885
D,gop,1493691
A,foo,100
B,bar,200
C,qux,300
D,gop,400
"
con <- textConnection(lines)
dat <- read.csv(con,header=FALSE)
close(con)
dat <- as.tibble(dat)
dat
,看起来像这样:
# A tibble: 8 × 3
V1 V2 V3
<fctr> <fctr> <dbl>
1 A foo 9394981
2 B bar 6826405
3 C qux 1074885
4 D gop 1493691
5 A foo 100
6 B bar 200
7 C qux 300
8 D gop 400
我怎么可以把它隐蔽于:
foo bar qux gop
9394981 6826405 1074885 1493691
100 200 300 400
答
创建行索引后,我们可以使用spread
tidyr
来处理duplicate
元件
library(tidyr)
library(dplyr)
dat %>%
select(-V1) %>%
group_by(V2) %>%
dplyr::mutate(i1 = row_number()) %>%
spread(V2, V3) %>%
select(-i1)
或者用dcast
从data.table
library(data.table)
dcast(setDT(dat), rowid(V2) ~ V2, value.var = "V3")[, V2 := NULL][]
答
总是有unstack
在基础R
unstack(form=V3 ~ V2, x=dat)
bar foo gop qux
1 6826405 9394981 1493691 1074885
2 200 100 400 300