2017-04-14 57 views
1

行轉換成列我有以下的數據幀(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 

回答

5

創建行索引後,我們可以使用spreadtidyr來處理duplicate元件

library(tidyr) 
library(dplyr) 
dat %>% 
    select(-V1) %>% 
    group_by(V2) %>% 
    dplyr::mutate(i1 = row_number()) %>% 
    spread(V2, V3) %>% 
    select(-i1) 

或者用dcastdata.table

library(data.table) 
dcast(setDT(dat), rowid(V2) ~ V2, value.var = "V3")[, V2 := NULL][] 
4

總是有unstack在基礎R

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

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