将文件列表加载到 R 数据框中
Load Filelist into R Dataframe
我正在处理目录中的所有文件,我想获取文件名的元数据,将其保存在数据框中,然后在处理目录后最终将数据框加载到 RSQLite table。
参考: and maybe
我不明白警告消息以及为什么文件名没有加载到数据框中:
setwd('C://tst//')
df <- data.frame("filename"= character(0), stringsAsFactors=FALSE)
for (fn in Sys.glob("tst*.dat")) {
print(fn)
df[nrow(df) + 1,] = list(fn)
}
输出:
[1] "tst1.dat"
[1] "tst2.dat"
[1] "tst3.dat"
Warning messages:
1: In `[<-.data.frame`(`*tmp*`, nrow(df) + 1, , value = list("tst1.dat")) :
replacement element 1 has 1 row to replace 0 rows
2: In `[<-.data.frame`(`*tmp*`, nrow(df) + 1, , value = list("tst2.dat")) :
replacement element 1 has 1 row to replace 0 rows
3: In `[<-.data.frame`(`*tmp*`, nrow(df) + 1, , value = list("tst3.dat")) :
replacement element 1 has 1 row to replace 0 rows
> dfrun
[1] filename
<0 rows> (or 0-length row.names)
>
此处无需增长数据框或使用循环。
假设您有这些文件:
ls ~/tst/*.dat
# tst1.dat tst2.dat tst3.dat
你可以写一个简单的R代码:
library(purrr)
library(dplyr)
my_files <- Sys.glob(file.path("~", "tst", "*.dat"))
df <- data.frame(filename=my_files, stringsAsFactors = FALSE)
decode_files <- function(x) {
# some function that processes a file
lines <- readLines(x)
substr(lines, 1, 5)
}
df %>%
mutate(output = map_chr(filename, decode_files))
这给你:
filename output
1 /Users/pedram/tst/tst1.dat hfrsh
2 /Users/pedram/tst/tst2.dat ifhju
3 /Users/pedram/tst/tst3.dat fdnfd
我正在处理目录中的所有文件,我想获取文件名的元数据,将其保存在数据框中,然后在处理目录后最终将数据框加载到 RSQLite table。
参考:
我不明白警告消息以及为什么文件名没有加载到数据框中:
setwd('C://tst//')
df <- data.frame("filename"= character(0), stringsAsFactors=FALSE)
for (fn in Sys.glob("tst*.dat")) {
print(fn)
df[nrow(df) + 1,] = list(fn)
}
输出:
[1] "tst1.dat"
[1] "tst2.dat"
[1] "tst3.dat"
Warning messages:
1: In `[<-.data.frame`(`*tmp*`, nrow(df) + 1, , value = list("tst1.dat")) :
replacement element 1 has 1 row to replace 0 rows
2: In `[<-.data.frame`(`*tmp*`, nrow(df) + 1, , value = list("tst2.dat")) :
replacement element 1 has 1 row to replace 0 rows
3: In `[<-.data.frame`(`*tmp*`, nrow(df) + 1, , value = list("tst3.dat")) :
replacement element 1 has 1 row to replace 0 rows
> dfrun
[1] filename
<0 rows> (or 0-length row.names)
>
此处无需增长数据框或使用循环。
假设您有这些文件:
ls ~/tst/*.dat
# tst1.dat tst2.dat tst3.dat
你可以写一个简单的R代码:
library(purrr)
library(dplyr)
my_files <- Sys.glob(file.path("~", "tst", "*.dat"))
df <- data.frame(filename=my_files, stringsAsFactors = FALSE)
decode_files <- function(x) {
# some function that processes a file
lines <- readLines(x)
substr(lines, 1, 5)
}
df %>%
mutate(output = map_chr(filename, decode_files))
这给你:
filename output
1 /Users/pedram/tst/tst1.dat hfrsh
2 /Users/pedram/tst/tst2.dat ifhju
3 /Users/pedram/tst/tst3.dat fdnfd