CuriousDude
CuriousDude

Reputation: 1117

How to access first element of a list of elements after strsplit?

I have a list of files saved as a list after running files <- list.files(pattern=".txt")

So when I run files I have something like the following:

AA1131.report.txt
BB1132.reprot.txt
CC0900.report.txt
.
.
.

I want to get just the first part of the filename before the .report.txt so in R I tried:

>files <- list.files(pattern=".txt")
>files <- strsplit(files, "\\.")
>files[[1]][1]
[1] "AA1131"

I was expecting:

[1] "AA1131"
[1] "BB1132"
[1] "CC0900"

Or some way to get them and save them as a list so I can use them as ID row names in my tibble for the first column.

Upvotes: 1

Views: 151

Answers (1)

akrun
akrun

Reputation: 887148

We need to loop over the list (from strsplit) and extract the first element

sapply(files, `[[`, 1)

The files[[1]] extracts only the first list element


Also, this can be done without an strsplit

trimws(files, whitespace = "\\..*")

or with sub

sub("\\..*", "", files)

Upvotes: 1

Related Questions