如何对含2列的list_sapply按行号升序排列?
按行号升序排列list_sapply的子元素
要实现将list_sapply中每个子矩阵按row列的值升序排列,直接用lapply()遍历每个子元素,结合order()函数排序即可:
# 对list_sapply的每个子元素按row列升序排序 sorted_list <- lapply(list_sapply, function(mat) { mat[order(mat[, "row"]), ] })
效果验证
以list_sapply的第二个子元素为例:
排序前:
list_sapply[[2]] # row col # [1,] 1 1 # [2,] 3 2 # [3,] 2 3
排序后:
sorted_list[[2]] # row col # [1,] 1 1 # [2,] 2 3 # [3,] 3 2
这段代码会自动处理所有子元素,无论每个子矩阵的行数多少,都能按行号1、2、3...的顺序重新排列行。
内容的提问来源于stack exchange,提问作者FrakTool
相关产品推荐
相关产品推荐

