首页 > 解决方案 > 如何在 R 中订购列表(夏皮罗测试结果)?

问题描述

我需要帮助来订购列表中的结果。下面是一个与我的数据相似的可重现样本:

da.ma <-matrix(1:22000, 10, 22) ## a sample matrix

n <-seq(max(length(da.ma[1,]))) ## naming cols and rows
for (i in n) {
    c.names <- paste("k", n, sep = "")
}
colnames(da.ma) <- c.names 

n.pdf <-seq(length(da.ma[,1]))
for (i in n.pdf) {
    r.names <- paste("text",n.pdf, sep ="")
}
rownames(da.ma) <- r.names
col.names <-names(da.ma[1,])

da.ma <-cbind(id =seq(length(da.ma[,1])), da.ma) ##adding the id col
library(tibble)
data <- as_tibble(da.ma)

library(rstatix)
in.anova <- data %>%  ## in-put data for anova & shapiro tests
  gather(key = "L", value = "V", all_of(col.names)) %>%
  convert_as_factor(id, L)


library(rstatix)  ##running the test
norm_sapiro <-in.anova %>%      
  group_by(L) %>%
  shapiro_test(V)

问题来了:

norm_sapiro

# A tibble: 22 x 4
   L     variable statistic     p
   <fct> <chr>        <dbl> <dbl>
 1 k1    V            0.970 0.892 ##the 1st  1000
 2 k10   V            0.970 0.892 ##the 10th 1000
 3 k11   V            0.970 0.892 ##the 11th 1000
 4 k12   V            0.970 0.892
 5 k13   V            0.970 0.892
 6 k14   V            0.970 0.892
 7 k15   V            0.970 0.892
 8 k16   V            0.970 0.892
 9 k17   V            0.970 0.892
10 k18   V            0.970 0.892
# ... with 12 more rows

我需要级别 ( L) 是有序的——这意味着级别名称的数字部分需要是有序的。换句话说,我需要根据从k1. 我想要的结果如下所示:

    # A tibble: 22 x 4
       L     variable statistic     p
       <fct> <chr>        <dbl> <dbl>
     1 k1    V            0.970 0.892
     2 k2    V            0.970 0.892
     3 k3    V            0.970 0.892
     4 k4    V            0.970 0.892
     5 k5    V            0.970 0.892
     6 k6    V            0.970 0.892
     7 k7    V            0.970 0.892
     8 k8    V            0.970 0.892
     9 k9    V            0.970 0.892
    10 k10   V            0.970 0.892
    11 k11   V            0.970 0.892
    12 k12   V            0.970 0.892
    13 k13   V            0.970 0.892
    14 k14   V            0.970 0.892
    # ... with 8 more rows

如何按顺序排列结果(k1、k2、k3、k4、k5...k22)。请注意,我也需要相应的值。

另外,我Ls在绘制情节时需要井井有条。为上述数据运行此代码(查看 X 轴)

ggboxplot(in.anova, x = "L", y = "V", add = "point")

标签: rlistanovanormal-distribution

解决方案


您可以L使用转换为因子stringr::str_sort然后排序:

df %>% 
  mutate(L = factor(L, str_sort(L, numeric = T))) %>% 
  arrange(L)

或与readr::parse_number

df[order(readr::parse_number(df$L)),]

如果L就这么简单,那么您可以简单地提取数字并执行以下操作:

df[order(as.numeric(gsub("k", "", df$L))),] # gsub("\\D+", "", df$L) also works

推荐阅读