【问题标题】:Create a datatable containing the Nth digit of each of a list of file names创建一个包含每个文件名列表的第 N 位的数据表
【发布时间】:2015-08-23 15:49:56
【问题描述】:

我有一个包含大型模型输出的文件列表。 我使用以下方法将这些加载为数据表:

files <- list.files(path.expand("/XYZ/"), pattern = ".*\\.rds", full.names =    TRUE)
dt<- as.data.table(files)

这个数据表“dt”只有 1 列,即文件名。 例如 XZY_00_34234.rds

每个文件名的第 50 和 51 个字符是一个数字。 我想为每个文件创建一个包含该 2 位数字的数据表。

我用过:

index <- as.data.table(as.integer(substr(dt,50,51)))

这为我提供了第一个文件的正确值。 我想我应该可以使用 apply 对文件的每一行运行它

我试过了:

integers <- as.data.table(apply(dt,1,as.integer(substr(50,51))))

但是得到:

substr(50, 51) 中的错误:缺少参数“stop”,没有默认值

任何建议都非常感谢!

【问题讨论】:

  • integers &lt;- as.data.table(apply(dt, 1, function(x) as.integer(substr(x, 50, 51))))

标签: r data.table apply


【解决方案1】:

如果您只有1 列,则可以将该列提取为vector 并直接在其上使用substr,而不是使用apply 循环。对于data.table,提取列是使用?Extract 函数[[$

 as.data.table(as.integer(substr(dt[[1]], 50, 51)))

或者

 as.data.table(as.integer(substr(dt$files, 50, 51)))

我注意到您正在从“文件”创建“dt”作为 data.table。 list.files() 的输出是vector,因此您可以先将substr vector 包装在as.data.table 中,而不是先创建data.table。

as.data.table(as.integer(files, 50, 51))

举个例子,

files <- c('ABC_25', 'DEF_39')
dt <- as.data.table(files)
as.integer(substr(dt[[1]], 5, 6))
#[1] 25 39
as.integer(substr(files, 5, 6))
#[1] 25 39

【讨论】:

    【解决方案2】:

    试试:

    integers <- as.data.table(apply(dt, 1, function(x) as.integer(substr(x, 50, 51))))
    

    apply 系列函数接受其他函数并在向量和数组上执行它们。这些函数已经定义了一些时间,但是在apply 函数中添加了一个有趣的特性,您可以第一次在该处编写函数。这样可以节省时间和击键。

    较窄的编程设置需要您的函数首先编写如下:

    fiftieth_char <- function(x) {
      as.integer(substr(x, 50, 51))
    }
    

    接下来,可以将该函数传递给apply 函数。

    apply(dt, 1, fiftieth_char)
    

    但是看看我们是如何将这两个步骤合二为一的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 2021-05-07
      • 2022-11-18
      • 1970-01-01
      相关资源
      最近更新 更多