重新组合数据框中的分类值

时间:2017-01-14 22:41:05

标签: r

我正在寻找一个建议:我正在尝试按变量值重新排序/分组数据框。

例如,转换本机数据帧VARS

Native data frame VARS:

这样的事情:

Into something like this:

到目前为止,我已经使用cbind / rbind尝试了for-loops,具体取决于数据的组织,聚合,应用等等。但是总会有一些皱纹阻止方法的运行。

我感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

首先,我想指出如何提供一个usefule示例,以及使用dput的原始数据将有很长的路要走,以获得反馈。那说:

For the dataset you showed:


 A <- structure(list(Var_Typer = c("cnt", "Cont", "cnt", "cnt", "fact", 
"fact", "Char", "Char", "Cont"), R_FIELD = c("Gender", "Age", 
"Activation", "WakeUpStroke", "ArMode", "PreHospActiv", "EMTag", 
"EMTdx", "EMTlams")), .Names = c("Var_Typer", "R_FIELD"), row.names = c(NA, 
-9L), class = "data.frame")

    > head(A)
  Var_Typer      R_FIELD
1       cnt       Gender
2      Cont          Age
3       cnt   Activation
4       cnt WakeUpStroke
5      fact       ArMode
6      fact PreHospActiv



 B <- apply(
       dcast(A, Var_Typer ~ R_FIELD, value.var = 'R_FIELD'), 1, function(i){
         ndf <- as.data.frame(rbind(i[complete.cases(i)]))
         colnames(ndf) <- c('Class',1:(length(ndf)-1))
         ndf
       }) %>% rbind.pages %>% (function(x){
              x[is.na(x)] <- "..."
              x
            })


   Class          1            2            3
 1  Char      EMTag        EMTdx          ...
 2   cnt Activation       Gender WakeUpStroke
 3  Cont        Age      EMTlams          ...
 4  fact     ArMode PreHospActiv          ...