【问题标题】:Compute the size of directory in R计算R中目录的大小
【发布时间】:2017-02-06 18:26:25
【问题描述】:

我想计算 R 中目录的大小。我尝试使用 list.info 函数,不幸的是它遵循符号链接,所以我的结果有偏差:

# return wrong size, with duplicate counts for symlinks
sum(file.info(list.files(path = '/my/directory/', recursive = T, full.names = T))$size)

我如何计算目录的文件大小,以便它给出与 Linux 相同的结果,例如以du -s 为例?

谢谢

【问题讨论】:

    标签: r directory size


    【解决方案1】:

    我终于用了这个:

    system('du -s')
    

    【讨论】:

    • 你能扩展一下吗?谢谢。
    • @MadmanLee R system() 函数调用系统命令。在 Linux 上,如果您使用du shell 命令调用它,它将打印出目录的大小(请参阅linux.die.net/man/1/du)。如果您在 windows 上运行,您将需要调用 windows shell 命令。
    【解决方案2】:
    system('powershell -noprofile -command "ls -r|measure -s Length"')
    

    参考资料:

    1. https://technet.microsoft.com/en-us/library/ff730945.aspx
    2. Get Folder Size from Windows Command Line
    3. https://stat.ethz.ch/R-manual/R-devel/library/base/html/system.html
    4. https://superuser.com/questions/217773/how-can-i-check-the-actual-size-used-in-an-ntfs-directory-with-many-hardlinks

    如果你有 cygwin,你也可以使用它;这使您可以使用 Linux 命令并获得可比较的结果。此外,在我上面给出的最后一个链接中使用Sysinternals 有一个很好的解决方案。

    【讨论】:

    • 实际上我在 Linux 上运行 R,但 system() 命令也应该可以运行。
    【解决方案3】:

    "file.size" 返回实际大小,磁盘上的大小是磁盘上实际占用的空间量。 检查这个以了解区别。 https://superuser.com/questions/66825/what-is-the-difference-between-size-and-size-on-disk 试试这个所有文件的大小:

     files<-list.files(path_of_directory,full.names = T)
     vect_size <- sapply(files, file.size)
     size_files <- sum(vect_size)
    

    【讨论】:

    • recursive 参数在这里丢失。
    【解决方案4】:

    健康的解决方案,对于检查包裹大小可能非常有用。

    dir_size <- function(path, recursive = TRUE) {
      stopifnot(is.character(path))
      files <- list.files(path, full.names = T, recursive = recursive)
      vect_size <- sapply(files, function(x) file.size(x))
      size_files <- sum(vect_size)
      size_files
    }
    
    cat(dir_size(find.package("Rcpp"))/10**6, "Mb")
    #> 14.81649 Mb
    

    reprex package (v2.0.0) 于 2021 年 6 月 26 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2011-03-11
      • 2018-03-29
      • 1970-01-01
      相关资源
      最近更新 更多