计算R中目录的大小

12

我想要在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 命令时的结果?

谢谢

5个回答

6
我最终使用了这个:
system('du -s')

你能详细说明一下吗?谢谢。 - MadmanLee
@MadmanLee R系统()函数调用系统命令。在Linux上,如果你使用du shell命令调用它,它会打印出目录的大小(参见https://linux.die.net/man/1/du)。如果你在Windows上运行,你需要调用一个Windows shell命令。 - Carmellose

5
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


1
实际上我正在Linux操作系统上运行R,但system()命令也应该能够在其上正常工作。 - Carmellose

5

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

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包 (v2.0.0)于2021-06-26创建


3

1
这里缺少 recursive 参数。 - polkas

1

最近我遇到了这个问题,以下是我的代码:

library(pacman)
p_load(fs,tidyfst)

sys_time_print({
  dir_info(your_directory_path) -> your_dir_info
})

your_dir_info %>% 
  summarise_dt(size = sum(size,na.rm = T))

当我第一次运行上面的代码时,它花费了大约3分钟来跟踪52G的文件(174,731个单独的文件)。后来当我再次运行时,只需要不到6秒钟就能完成。这太神奇了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接