【问题标题】:sorting input files on the basis of number of observations根据观察次数对输入文件进行排序
【发布时间】:2015-04-17 10:31:16
【问题描述】:

我在一个目录中有多个具有不同观察次数的文件,需要根据观察次数对文件进行排序,并像序列 file1、file2、file3.... 等一样保存它们。 例如,假设我有 4 个文件,观察数为 5、6、3、2,分别命名为 abc、ikl、hj、op。现在,经过排序和重命名的文件应按以下方式保存在目录中。 file1 是观察次数为 2 的文件,file2 应该是观察次数为 3 的文件,file3 为 5,file4 为 6。我有什么办法可以在 R 中做到这一点?

 abc           ikl           nj                 op

1  2  3       20 1  2        76 43 56        233 123 56
4  5  6       10 5  8        12 11 10        564 15  45
7  8  9       3 77  9        4  2  1
10 11 12      12 8 90
13 14 15      5  6  8 
              2  1  7

重命名后:

file1          file2          file3          file4

233 123 56     76 43 56       1  2  3       20 1 2
564 15 45      12 11 10       4  5  6       10 5 8
                4  2  1       7  8  9       3 77 9
                              10 11 12     12 8 90
                              13 14 15      5 6 8
                                            2 1 7

请注意 abc、ikl、hj、op、file1、file2、file3、file4 是文件名。

【问题讨论】:

  • 你能举一个数据例子吗?谢谢!
  • @RuthgerRighart 我已经添加了一个示例。请看一看。谢谢!

标签: r


【解决方案1】:

很多代码,但它可以完成工作:

# Crate some data frames
abc <- data.frame(matrix(0, 5, 3))
ikl <- data.frame(matrix(1, 6, 3))
nj <- data.frame(matrix(2, 3, 3))
op <- data.frame(matrix(3, 2, 3))

# This is where your code starts
# put them in a list
l <- list(abc, ikl, nj, op)

# find the number of observations for each data.frame
l1 <- sapply(l, function(x) dim(x)[1])


for(i in 1:length(l)){
  assign(paste0("file", i), l[order(l1)][[i]])
}

【讨论】:

    猜你喜欢
    • 2014-07-11
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2023-03-31
    • 2016-07-04
    • 2020-11-17
    • 2020-05-22
    相关资源
    最近更新 更多