R - 对列表中的每个数据框执行融合

标签 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"))

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

感谢阅读!

编辑:我突然的话。

最佳答案

这里有几点需要指出。

首先,您确实应该使用 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)

关于R - 对列表中的每个数据框执行融合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20012471/

相关文章:

R-如何将文件内容转储到控制台输出?

r - 在 Y 中丢失数据的回归后预测.lm

回程数据的 R 组列

r - 以 PDF 和 PNG 格式保存图表,但在最终文档中使用 PDF 文件

reshape 数据框 --- 将行更改为列

python - 如何使用 numpy.ndarray 合并特定轴而不会产生歧义

r - 如何在 Likert 图的每个条形上输出正确的百分比?

r - 为多个时间序列创建“"Yesterday' s Value”变量

python - 使用 numpy.reshape() 反转 skimage view_as_blocks()

R对数据表的特殊 reshape