我在一个目录中有几个数据文件(所有 tsvs)。一个数据文件将如下所示:
Killed Rick Darryl Herschel Tyrese Shane
Zombies 200 300 20 4 100
People 10 2 0 0 0
Dogs 0 0 0 0 0
下一个数据文件是这样的:
Killed Jon Rob Varys Ned Joeffry Mormont
Whites 1 0 0 0 0 0
People 0 10 1 30 0 100
我想合并它,这样数据文件会像这样读取:
Killed Variable Value
Zombies Rick 200
Zombies Darryl 300
Zombies Herschel 20
Zombies Tyrese 4
Zombies Shane 100
People Rick 10
People Darryl 2
People Herschel 0
People Tyrese 0
People Shane 0
Dogs Rick 0
Dogs Darryl 0
Dogs Herschel 0
Dogs Tyrese 0
Dogs Shane 0
Whites Jon 1
Whites Rob 0
Whites Varys 0
Whites Ned 0
Whites Joeffry 0
Whites Mormont 0
People Jon 0
People Rob 10
People Varys 1
People Ned 30
People Joeffry 0
People Mormont 100
我想通过目录解析并将所有数据加载到 R 中,然后使用 reshape 包融化每个数据框。我会使用 rbind 将所有数据帧组合成一个数据帧。这是我到目前为止的代码:
library(reshape)
filenames <- list.files(pattern='*.tsv')
names <- substr(filenames,1, nchar(filenames)-4)
newmelt <- function(x) {
x <- melt(x, id=c("ID_REF"))
}
for (i in names){
filepath <- file.path(paste(i,".tsv", sep=""))
assign(i, read.csv(filepath, sep="\t"))
}
sapply(names(names), newmelt)
我知道我可以用这个得到我想要的结果:
test <- read.csv("marvel.tsv", sep="\t")
test.m <- melt(test, id=c("Killed"))
但我不确定如何将其应用于列表中的所有数据框。
感谢阅读!
编辑:我突然的话。
最佳答案
这里有几点需要指出。
首先,您确实应该使用 reshape2,reshape 已不再开发。
其次,避免使用assign
(通常),尤其是在这些情况下。它不是很“R-ish”,它会导致坏习惯和难以调试的问题。
第三,如果你的文件真的是制表符分隔的,不要使用read.csv
(仔细阅读关于read.csv
的文档说明,这不是你想要的!),使用 read.table
。
我会更像这样处理:
library(reshape2)
filenames <- list.files(pattern='*.tsv')
myfun <- function(x){
dat <- read.table(x,sep = "\t",header = TRUE)
melt(dat,id.vars = "Killed")
}
#Just iterate over the file paths
# calling one function that reads in the file and melts
out <- lapply(filenames,myfun)
#Put them all together into one data frame
out <- do.call(rbind,out)
关于R - 对列表中的每个数据框执行融合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20012471/