Create a datatable containing the Nth digit of each of the file name lists

I have a list of files containing output from a large model. I load them as data using:

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

This datatable "dt" has only 1 column, file name. e.g. XZY_00_34234.rds

The 50th and 51st characters of each file name is a number. I want to create a datatable containing this 2 digit number for each file.

I used:

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

This gives me the correct value for the first file. I think I should use the apply application to run it against every line of the file

I tried:

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

But we get:

Error in substr (50, 51): missing "stop" argument, no default value

Any suggestions are gratefully accepted!

+4
source share
2 answers

Try:

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)

, .

+2

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 'files'. list.files() vector, data.table substr vector as.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
+1

All Articles