簡體   English   中英

數據格式轉換與R中的字符串拆分結合使用

[英]Data format conversion to be combined with string split in R

我有以下數據框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
.....

因此,轉換將涉及的分割gp10month從2列,等:原始數據幀的7 oridf這樣我可以用下面的命令繪制它:

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

如何轉換這些數據? 我嘗試了melt命令,但是無法將其與strsplit命令結合使用。

首先,我將像您一樣使用融化。

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命令來繪制它

在此處輸入圖片說明

使用gather從tidyr包從廣角轉換為長,然后用separate從同一個包到分離group_month柱成groupmonth列。 最后,使用來自dplyr的mutate從tidyr提取smf extract_numeric提取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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM