【问题标题】:Transform dataframe in R: Resolve ambiguity, save rows在 R 中转换数据框:解决歧义,保存行
【发布时间】:2014-07-18 15:45:34
【问题描述】:

我想从这里转换一个数据框

original <-data.frame(Treatment=c("Drug","Drug","Drug","Placebo","Placebo","Placebo"),Group=c(1,2,3,1,2,3),Performance=c(4,6,3,2,5,1))

到这里:

transformed <- data.frame(Group=c(1,2,3),PerformanceDrug=c(4,6,3),PerformanceTreatment=c(2,5,1))

我尝试了 package reshape 中的 melt-function,但还没有找到解决方案。你能帮帮我吗?

【问题讨论】:

    标签: r dataframe transformation reshape


    【解决方案1】:

    您的数据已经“融化”了,所以只需使用dcast

    library(reshape2)
    dcast(original, Group ~ Treatment, value.var="Performance")
    #   Group Drug Placebo
    # 1     1    4       2
    # 2     2    6       5
    # 3     3    3       1
    

    您也可以直接使用 base R 的reshape()

    reshape(original, direction = "wide", idvar="Group", timevar="Treatment")
    #   Group Performance.Drug Performance.Placebo
    # 1     1                4                   2
    # 2     2                6                   5
    # 3     3                3                   1
    

    最后一个选项:

    library(dplyr)
    library(tidyr)
    original %>% spread(Treatment, Performance)
    

    【讨论】:

    • @akrun,如果我将xtabs(Performance ~ Group + Treatment, original) 添加到选项中,我会得到另一个+1 :-)
    • 好吧,可能其他人会,因为我不能双重投票
    猜你喜欢
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    相关资源
    最近更新 更多