读取错误并将数据文件夹合并到一个数据帧中

时间:2016-08-17 05:00:09

标签: r

如果有帮助,我在Macbook Pro OS El Captain上运行R 3.3.1 ...

我正在尝试读取类似数据文件的文件夹。我已经检查了目录,文件应该是它们的位置:

list.files('../data/')
 [1] "B101.txt"   "B101p2.txt" "B116.txt"   "B6.txt"     "B65.txt"    "B67.txt"    "B67p2.txt" 
 [8] "B70.txt"    "B71.txt"    "B71p2.txt"  "B95.txt"    "B95p2.txt"  "B96.txt"    "B96p2.txt"
[15] "B98.txt"    "B98p2.txt"  "B99.txt"    "B99p2.txt" 

以下是我的代码和错误:

a = ldply(
    .data = list.files(
        path = '../data/'
            )
    , .fun = function(x){
        to_return = read.table(
            file = x
            , skip = 20
            , sep = '\t'
            , fill = TRUE
                )
        return(to_return)
            }
    , .progress = 'text'
)

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'B101.txt': No such file or directory

我不知道问题是什么,因为对这些错误的所有搜索建议修复目录。我还检查了数据文件,并可以使用以下方式读取单个文件:

read.table('../data/B101.txt', skip = 20, sep = '\t', fill=TRUE)

有人可以帮我解决整个文件夹中的阅读问题。我试图用少量文件来整理脚本但是需要它来运行更大的数字,因此逐个阅读它们并不实际。感谢。

1 个答案:

答案 0 :(得分:1)

默认情况下,list.files仅返回 文件名 ,不包括前导(相对或绝对)路径(如果有)。在处理可能位于其他目录中的文件时,您需要包含full.names = TRUE

a = ldply(
    .data = list.files(
        path = '../data/',
        full.names = TRUE
            )
    , .fun = function(x){
        to_return = read.table(
            file = x
            , skip = 20
            , sep = '\t'
            , fill = TRUE
                )
        return(to_return)
            }
    , .progress = 'text'
)