R - 在列表中的每个数据帧上执行熔化

时间:2013-11-15 23:30:42

标签: r reshape

我在目录中有几个数据文件(所有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"))

但我不确定如何在列表中的所有数据框上应用它。

感谢您阅读!

编辑:我突然说了一句话。

1 个答案:

答案 0 :(得分:6)

这里有几点需要指出。

首先,你真的应该使用 reshape2 重塑不再处于开发阶段。

其次,避免使用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)