【问题标题】:Data format conversion to be combined with string split in R数据格式转换与 R 中的字符串拆分相结合
【发布时间】:2014-07-13 03:30:04
【问题描述】:

我有以下数据框oridf

test_name   gp1_0month  gp2_0month  gp1_1month  gp2_1month  gp1_3month  gp2_3month
Test_1  136 137 152 143 156 150
Test_2  130 129 81  78  86  80
Test_3  129 128 68  68  74  71
Test_4  40  40  45  43  47  46
Test_5  203 201 141 134 149 142
Test_6  170 166 134 116 139 125

oridf <- structure(list(test_name = structure(1:6, .Label = c("Test_1", 
"Test_2", "Test_3", "Test_4", "Test_5", "Test_6"), class = "factor"), 
    gp1_0month = c(136L, 130L, 129L, 40L, 203L, 170L), gp2_0month = c(137L, 
    129L, 128L, 40L, 201L, 166L), gp1_1month = c(152L, 81L, 68L, 
    45L, 141L, 134L), gp2_1month = c(143L, 78L, 68L, 43L, 134L, 
    116L), gp1_3month = c(156L, 86L, 74L, 47L, 149L, 139L), gp2_3month = c(150L, 
    80L, 71L, 46L, 142L, 125L)), .Names = c("test_name", "gp1_0month", 
"gp2_0month", "gp1_1month", "gp2_1month", "gp1_3month", "gp2_3month"
), class = "data.frame", row.names = c(NA, -6L))

我需要将其转换为以下格式:

test_name   month   group   value
Test_1      0       gp1     136
Test_1      0       gp2     137
Test_1      1       gp1     152
Test_1      1       gp2     143
.....

因此,转换将涉及从原始数据框oridf 的 2:7 列拆分 gp10month 等,以便我可以使用以下命令对其进行绘制:

qplot(data=newdf, x=month, y=value, geom=c("point","line"), color=test_name, linetype=group)

如何转换这些数据?我尝试了melt 命令,但我无法将它与strsplit 命令结合使用。

【问题讨论】:

    标签: r ggplot2 dataframe


    【解决方案1】:

    首先我会像你一样使用melt。

    library(reshape2)
    mm <- melt(oridf)
    

    那么您也可以在reshape2 库中使用colsplit 函数。这里我们在变量列上使用它来分割下划线和月份中的“m”(忽略其余部分)

    info <- colsplit(mm$variable, "(_|m)", c("group","month", "xx"))[,-3]
    

    然后我们可以重新组合数据

    newdf <- cbind(mm[,1, drop=F], info, mm[,3, drop=F])
    
    # head(newdf)
    #   test_name group month value
    # 1    Test_1   gp1     0   136
    # 2    Test_2   gp1     0   130
    # 3    Test_3   gp1     0   129
    # 4    Test_4   gp1     0    40
    # 5    Test_5   gp1     0   203
    # 6    Test_6   gp1     0   170
    

    我们可以使用上面提供的qplot 命令绘制它

    【讨论】:

      【解决方案2】:

      使用 tidyr 包中的gather 将宽转换为长,然后使用同一包中的separategroup_month 列分隔为groupmonth 列。最后使用mutate from dplyr smf extract_numeric from tidyr 提取month 的数字部分。

      library(dplyr)
      # devtools::install_github("hadley/tidyr")
      library(tidyr)
      
      newdf <- oridf %>%
         gather(group_month, value, -test_name) %>% 
         separate(group_month, into = c("group", "month")) %>% 
         mutate(month = extract_numeric(month))
      

      【讨论】:

      • 感谢您的代码。我无法连接到 r-cran 存储库来安装 dplyr 和 tidyr。我会尽快测试。
      • @rnso 据我所知,tidyr 还没有在 CRAN 上,您可以使用 devtools 包安装它:install_github("hadley/tidyr")
      猜你喜欢
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多