R:在基于多列的数据帧中使用排序函数

R:在基于多列的数据帧中使用排序函数,r,R,我是一名心脏病专家,喜欢用R编码——我对数据帧的排序有一个真正的问题,我怀疑解决方案真的很简单 我有一个数据框架,包含多个研究的总结值。大多数研究只有一个摘要值(df$summary)。然而,正如您所见,研究A有三个汇总值(df$no.of.estimate)。见下文 study <- c("E", "A", "F", "A", "B", "A", "C", "D") no.of.estimate <- c(1, 2, 1, 3, 1, 1, 1, 1) summary <-

我是一名心脏病专家,喜欢用R编码——我对数据帧的排序有一个真正的问题,我怀疑解决方案真的很简单

我有一个数据框架,包含多个研究的总结值。大多数研究只有一个摘要值(df$summary)。然而,正如您所见,研究A有三个汇总值(df$no.of.estimate)。见下文

study <- c("E", "A", "F", "A", "B", "A", "C", "D")
no.of.estimate <- c(1, 2, 1, 3, 1, 1, 1, 1)
summary <- c(1, 2, 3, 5, 6 ,7 ,8 ,9)
df <- data.frame(study, no.of.estimate, summary)
你可以试试

library(dplyr)
df %>% 
     mutate(study=factor(study, levels=unique(study))) %>%
     arrange(study,no.of.estimate)
  #  study no.of.estimate summary
  #1     E              1       1
  #2     A              1       7
  #3     A              2       2
  #4     A              3       5
  #5     F              1       3
  #6     B              1       6
  #7     C              1       8
  #8     D              1       9
基本R
方法

df$study <- factor(df$study, levels=unique(df$study))
df[with(df, order(study, no.of.estimate)), ]

df$study这是我的
数据表
在保持列不变并创建新索引的同时尝试(尽管先看我的注释)。它的主要优点是,您可以通过引用更新数据集,而不是创建新的副本

library(data.table)
setorder(setDT(df)[, indx := .GRP, study], indx, no.of.estimate)[]
#    study no.of.estimate summary indx
# 1:     E              1       1    1
# 2:     A              1       7    2
# 3:     A              2       2    2
# 4:     A              3       5    2
# 5:     F              1       3    3
# 6:     B              1       6    4
# 7:     C              1       8    5
# 8:     D              1       9    6

您一定注意到,通过使用
cbind
,您创建了一个矩阵,其中列作为字符类。使用
data.frame(研究,估计数…
您不想按
sudy
no.of.estimate
对整个数据集进行排序,而只是在
no.of.estimate
有多个值的情况下?你似乎把这件事复杂化了一点。看起来你可以用(df,order(study,no.of.estimate)),]来做
df,
,不过先看看@akruns comment。
df <- structure(list(study = structure(c(5L, 1L, 6L, 1L, 2L, 1L, 3L, 
4L), .Label = c("A", "B", "C", "D", "E", "F"), class = "factor"), 
no.of.estimate = c(1, 2, 1, 3, 1, 1, 1, 1), summary = c(1, 
2, 3, 5, 6, 7, 8, 9)), .Names = c("study", "no.of.estimate", 
"summary"), row.names = c(NA, -8L), class = "data.frame")
df1 <- structure(list(study = structure(c(5L, 1L, 1L, 1L, 6L, 2L, 3L, 
4L), .Label = c("A", "B", "C", "D", "E", "F"), class = "factor"), 
no.of.estimate = c(1, 1, 2, 3, 1, 1, 1, 1), summary = c(1, 
7, 2, 5, 3, 6, 8, 9)), .Names = c("study", "no.of.estimate", 
"summary"), row.names = c(NA, -8L), class = "data.frame")
library(data.table)
setorder(setDT(df)[, indx := .GRP, study], indx, no.of.estimate)[]
#    study no.of.estimate summary indx
# 1:     E              1       1    1
# 2:     A              1       7    2
# 3:     A              2       2    2
# 4:     A              3       5    2
# 5:     F              1       3    3
# 6:     B              1       6    4
# 7:     C              1       8    5
# 8:     D              1       9    6