r - 如何在 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")
解决方案
您可以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
推荐阅读
- c# - 实例化的预制件在层次结构中显示为非活动
- python - 如何找到合适的聚类算法来聚类我的数据?
- excel - 如何将唯一ID的每个值乘以Excel中不同工作表中的相同三个值
- reactjs - 如何使用 React-testing-library 测试使用自定义钩子的组件?
- c# - Microsoft.CSharp.Core.targets(70,5):错误:内存不足
- regex - 使用正则表达式将单词组与任何其他单词匹配
- angular - Ionic 6 Angular,Ion-Slide.slideNext() 在自定义按钮事件中不起作用
- php - 遍历对象图时内存泄漏
- google-sheets-api - 当数据集大于 50k 个字符时,使用应用程序脚本将 csv 数据导入谷歌表格
- bash - 尝试使用 bash 脚本自动化我的 docker 容器会给我一个 OCI 运行时错误