【发布时间】:2019-04-03 11:36:22
【问题描述】:
我有一个包含纵向信息(长格式)的数据框。
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) 的“是”计数的百分比,以便具有如下内容:
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"))
谢谢!
【问题讨论】: