如何使用dplyr将行转换为列

时间:2017-04-14 14:14:21

标签: r dplyr reshape tidyverse

我有以下数据框(tibble):

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

2 个答案:

答案 0 :(得分:6)

我们可以在创建行索引后使用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][]

答案 1 :(得分:4)

基础R总是unstack

unstack(form=V3 ~ V2, x=dat)

      bar     foo     gop     qux
1 6826405 9394981 1493691 1074885
2     200     100     400     300