【问题标题】:How to convert rows into columns using dplyr [duplicate]如何使用 dplyr 将行转换为列 [重复]
【发布时间】:2017-09-10 19:39:10
【问题描述】:

我有以下数据框(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

【问题讨论】:

    标签: r dplyr reshape tidyverse


    【解决方案1】:

    我们可以在创建行索引后使用tidyr 中的spread 来处理duplicate 元素

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

    或者使用来自data.tabledcast

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

    【讨论】:

      【解决方案2】:

      在基本 R 中总是有 unstack

      unstack(form=V3 ~ V2, x=dat)
      
            bar     foo     gop     qux
      1 6826405 9394981 1493691 1074885
      2     200     100     400     300
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-09
        • 1970-01-01
        • 1970-01-01
        • 2021-02-26
        • 2015-08-06
        • 2013-10-01
        • 2020-11-14
        相关资源
        最近更新 更多