繁体   English   中英

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

[英]R - Perform Melt on Each Data Frame in a List

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

但是我不确定如何将其应用于列表中的所有数据框。

感谢您的阅读!

编辑:我突然说。

这里有两点要指出。

首先,您确实应该使用reshape2reshape不再在开发中。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM