【问题标题】:How to set colnames and rownames when you read bunch of files from a directory into R?将目录中的一堆文件读入R时如何设置列名和行名?
【发布时间】:2014-04-28 13:57:53
【问题描述】:

我有一个目录,里面有很多文件。我正在尝试读取所有文件并选择每个文件的第二列并使用 rbind 创建矩阵。但问题是创建矩阵后,其中没有列名和行名。 基本上,行名应该是我阅读的文件名,rbind 它是第二列。 colnames 应该是其中一个文件的第一列。

这是我的努力:

nm <- list.files(path="path/to/file")
MyMatrix<-do.call(rbind, lapply(nm, function(x) read.table(file=x)[, 2]))

【问题讨论】:

  • 您是否尝试过将行名称设置为您想要的? row.names(MyMatrix) &lt;- nm...

标签: r


【解决方案1】:

虚假数据设置(例如,您的所有文件都在testdir 目录中)

my.data <- Indometh
write.csv(my.data, file = "testdir/test1.csv", row.names = FALSE)
my.data$time <- my.data$time + 1
write.csv(my.data, file = "testdir/test2.csv", row.names = FALSE)
my.data$time <- my.data$time + 1
write.csv(my.data, file = "testdir/test3.csv", row.names = FALSE)

那么你的周期需要做一些改变

nm <- list.files(path="testdir")
my.file <- paste("testdir", nm, sep="/")
MyDataFrame<-do.call(cbind, lapply(my.file, function(x) {
   col2name <- gsub( "\\..+$","", basename(x))
   my.col <- data.frame(read.csv(file=x)[, 2])
   names(my.col) <- col2name
   my.col

}))

MyDataFrame

这里用read.csv 完成,根据您的需要调整它:)

HTH,卢卡

【讨论】:

    猜你喜欢
    • 2017-09-20
    • 2022-08-17
    • 1970-01-01
    • 2017-02-16
    • 2014-08-20
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多