我有一个有数千个数据文件的文件夹(没有标签,只有列号)。我还有一个CSV,其中包含文件夹中的文件名、列标题号和列标签。数字3是我所需要的!文件中的数据列是而不是,顺序相同。因此,我希望将正确的列名与每个数据文件匹配,并通过匹配它们将它们绑定在一起(就像查找表,但对于头)。
下面是“查找头”虚拟数据:
filenames <- c("file1", "file1", "file1","file2","file2", "file2", "file3", "file3", "file3")
num <- c(1, 2, 3, 1, 2, 3, 1, 2, 3)
label <- c("AA", "BB", "CC", "AA", "BB", "CC", "BB", "CC", "AA")
header <- data.frame(filenames,num,label)
> header
filenames num label
1 file1 1 AA
2 file1 2 BB
3 file1 3 CC
4 file2 1 AA
5 file2 2 BB
6 file2 3 CC
7 file3 1 BB
8 file3 2 CC
9 file3 3 AA
以下是文件的样子:
> file1
1 2 3
2.3 1.5 202.4
> file2
1 2 3
2.1 1.0 200.8
> file3
1 2 3
1.0 208.1 2.1
然后,我循环遍历目录中的这些文件,并根据列名将它们绑定在一起。
files <- dir("my dir")
z <- NULL
for (file in files) {
x <- read.table(file.path("my dir", file), as.is=TRUE)
names(x) <- c("AA","BB","CC") #this is where I'd like to name according to matching column
z <- rbind(z,x) #bind current file to previous processed file
}
所有三个文件的期望结果!
> z
AA BB CC
2.3 1.5 202.4
2.1 1.0 200.8
2.1 1.0 208.1
发布于 2018-03-10 11:14:16
我们使用mget
获得'file‘对象的值(假设它在全局环境中),split
'header’通过'filenames‘列,而map2
(来自purrr
)使用'y’中带有'num‘列的列名设置相应的'label’列名。
library(dplyr)
library(purrr)
mget(paste0('file', 1:3)) %>%
map2_df(., header %>%
split(factor(.$filenames, levels = unique(.$filenames))),
~ set_names(.x, .y$label[match(names(.x), .y$num)]))
# AA BB CC
#1 2.3 1.5 202.4
#2 2.1 1.0 200.8
#3 2.1 1.0 208.1
https://stackoverflow.com/questions/49212950
复制