Home > OS >  Efficient way of assigning attribute table names based on a partial list element name
Efficient way of assigning attribute table names based on a partial list element name

Time:03-27

I have a list with path names as the element names in list l1.

# File List
l1 <- list(2,3,4,5)
names(l1) <- c("C:/Users/2013_mean.csv",
               "C:/Users/2013_median.csv",
               "C:/Users/2015_mean.csv",
               "C:/Users/2015_median.csv")


I would like to assign a attribute table to the list that looks similar to the following in a more efficient manner. I would like to extract only a portion of the path name from the elements in l1 assign them to its respective componenent. For example: I would like to "grab" the name "2013_mean" from "C:/Users/2013_mean.csv" in l1 and assign it to that element in the attribute table. Is there a more efficient way of doing this?

attributes(l1) <- data.frame(id = c("2013_mean", "2013_median", "2015_mean", "2015_median")
                             )

attributes(l1)

CodePudding user response:

We can use basename on the names of the list to extract the substring

attributes(l1) <- data.frame(id = sub("\\.csv", "", basename(names(l1))))

-output

> l1
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

[[4]]
[1] 5

attr(,"id")
[1] "2013_mean"   "2013_median" "2015_mean"   "2015_median"

Or another option is basename file_path_sans_ext

tools::file_path_sans_ext(basename(names(l1)))
[1] "2013_mean"   "2013_median" "2015_mean"   "2015_median"
  • Related