Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading