如何将数据框重塑为分类数据的百分比

时间:2019-04-03 11:36:22

标签: r dataframe

我有一个包含纵向信息(长格式)的数据框。

mydata<-structure(list(record_id = c("a", "a", "a", "b", "b", "b", "c", "c","c"),event = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label =c("e2", "e3", "e4"), class = "factor"), var1 = structure(c(2L, 1L, 1L, 1L,1L, 1L, 1L, 1L, 1L), .Label = c("no", "yes"), class = "factor"),var2 =structure(c(1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("no", "yes"), class = "factor"), var3 = structure(c(2L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 1L),.Label = c("no", "yes"), class = "factor")), row.names = c(NA, -9L), class= c("tbl_df", "tbl", "data.frame"))

我需要将这些数据转换为一个数据帧,以根据事件(e2,e3,e4)汇总每个变量(var1,var2,var3)的“是”计数的百分比,以具有如下所示: / p>

mydata_result<-structure(list(Event = structure(c(1L, 1L, 1L, 2L, 2L, 2L,3L, 3L, 3L), .Label = c("e2", "e3", "e4"), class = "factor"), Variable =structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("var1", "var2", "var3"), class = "factor"), percentage_of_yes = c(0.33, 0.33, 0.66, 0, 0.33, 0.66, 0, 0, 0)), row.names = c(NA, -9L), class = c("tbl_df", "tbl","data.frame"))

谢谢!

2 个答案:

答案 0 :(得分:2)

使用tidyverse,我们可以转换为长格式,按变量和事件分组,然后进行百分比计数,即

library(tidyverse)

mydata %>% 
  gather(var, val, -c(1:2)) %>% 
  group_by(event, var) %>% 
  summarise(new = sum(val == 'yes')/n())

给出,

# A tibble: 9 x 3
# Groups:   event [?]
  event var     new
  <fct> <chr> <dbl>
1 e2    var1  0.333
2 e2    var2  0.333
3 e2    var3  0.667
4 e3    var1  0    
5 e3    var2  0.333
6 e3    var3  0.667
7 e4    var1  0    
8 e4    var2  0    
9 e4    var3  0    

答案 1 :(得分:2)

这里是data.table

的替代方法
library(data.table)
melt(setDT(mydata), id.vars = c("record_id", "event"))[, 
 .(percentage_of_yes = round(mean(value == "yes"), 3)), 
        .(event, Variable = variable)]
#    event Variable percentage_of_yes
#1:    e2     var1             0.333
#2:    e3     var1             0.000
#3:    e4     var1             0.000
#4:    e2     var2             0.333
#5:    e3     var2             0.333
#6:    e4     var2             0.000
#7:    e2     var3             0.667
#8:    e3     var3             0.667
#9:    e4     var3             0.000