【问题标题】:Reshape a data frame to long format by expanding elements of an existing column通过扩展现有列的元素将数据框重塑为长格式
【发布时间】:2014-02-27 16:43:48
【问题描述】:

我有一个包含 3 列的数据框:

A <- c("stringA", "stringA", "stringB", "stringB")
B <- c(1, 2, 1, 2)
C <- c("abcd", "abcd", "abcde", "bbc")

df <- data.frame(A, B, C)

> test
        A B     C
1 stringA 1  abcd
2 stringA 2  abcd
3 stringB 1 abcde
4 stringB 2   bbc

我想重新格式化,使 B 列成为行名,并将 C 列中的值拆分为单个字母以获取:

A    1    2   
stringA    a    a
stringA    b    b
stringA    c    c
stringA    d    d
stringB    a    b
stringB    b    b
stringB    c    c
stringB    d    NA
stringB    e    NA

【问题讨论】:

    标签: r reshape reshape2


    【解决方案1】:

    这是一种使用“data.table”和“reshape2”的方法。确保您首先使用至少 1.8.11 版的“data.table”包。

    library(reshape2)
    library(data.table)
    packageVersion("data.table")
    # [1] ‘1.8.11’
    
    DT <- data.table(df, key="A,B")
    DT <- DT[, list(C = unlist(strsplit(as.character(C), ""))), by = key(DT)]
    DT[, N := sequence(.N), by = key(DT)]
    dcast.data.table(DT, A + N ~ B, value.var="C")
    #          A N 1  2
    # 1: stringA 1 a  a
    # 2: stringA 2 b  b
    # 3: stringA 3 c  c
    # 4: stringA 4 d  d
    # 5: stringB 1 a  b
    # 6: stringB 2 b  b
    # 7: stringB 3 c  c
    # 8: stringB 4 d NA
    # 9: stringB 5 e NA
    

    如果您更喜欢坚持使用 base R,则方法有些相似:

    ## Split the "C" column up
    X <- strsplit(as.character(df$C), "")
    
    ## "Expand" your data.frame
    df2 <- df[rep(seq_along(X), sapply(X, length)), ]
    
    ## Create an additional "id"
    df2$id <- with(df2, ave(as.character(A), A, B, FUN = seq_along))
    
    ## Replace your "C" values
    df2$C <- unlist(X)
    
    ## Reshape your data
    reshape(df2, direction = "wide", idvar=c("A", "id"), timevar="B")
    #           A id C.1  C.2
    # 1   stringA  1   a    a
    # 1.1 stringA  2   b    b
    # 1.2 stringA  3   c    c
    # 1.3 stringA  4   d    d
    # 3   stringB  1   a    b
    # 3.1 stringB  2   b    b
    # 3.2 stringB  3   c    c
    # 3.3 stringB  4   d <NA>
    # 3.4 stringB  5   e <NA>
    

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2012-03-25
      相关资源
      最近更新 更多