'Change row names in data frame in R

I've got the following code to iterate through directory/subdirectory, pick out certain files, read a value in them, and populate a new data frame with those values. It works, with a few issues...

Here's the code

   wd = setwd("/Users/TK/Downloads/DataCSV")

Groups <- list.dirs(path = wd, full.names = TRUE, recursive = FALSE)
Subj <- list.dirs(path = Groups, full.names = TRUE, recursive = FALSE)

section_area_vector <- numeric()

for(i in Subj)  {
  setwd(i)
  section_area <- list.files(path = i, pattern = "section_area", 
                             full.names = FALSE, recursive = TRUE)
  read_area <- sapply(section_area, function(x)read.csv(x)[1,2])
  total_area_subj <- sum(read_area)
  section_area_vector <- rbind(section_area_vector, total_area_subj)
  
  }

section_area_data <- as.data.frame(section_area_vector)
colnames(section_area_data)[colnames(section_area_data) == 
                                   "V1"] <- "Area"

The output looks like this table:

sample output table

How do I get the row names to appear as subj.1, subj.2, subj.3

Also, I seem to have to run the code twice, with the first time it not working (basically a null result), but the second time it works and yields the table - any ideas why this might be?

Also, is this the best way to write this task, or is there something more elegant? I know "for loops" are frowned upon as they are slow (eventually there will be lots of data to work with)...tried using sapply functions but got lost in the syntax. Would love some suggestions if this code can be improved.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source