Reputation: 5068
I'm trying to organise a growing R project which my team has been collaborating on. My initial thought is to put all the script names into a list
x = list.files(recursive = TRUE)
and put it in a spreadsheet so I can go through, thinking about which scripts are obsolete, and which ones probably should form separate projects.
Thankfully, most scripts have a one-line comment at the top which summarises the scripts contents.
Is there an R way to put all those first-row comments in a dataframe? i.e. is there a function in R for extracting lines of code from a filename?
Upvotes: 1
Views: 370
Reputation: 9313
Try the following:
myRFiles = list.files(pattern = "*.R")
firstLines = lapply(myRFiles, FUN = read.table, nrows = 1, sep = "\n")
df = do.call(rbind, firstLines)
myRFiles
contain all your R files (change the pattern for your case).
With read.table
you can read the first row (nrows=1
) and use the newline character (\n
) as separator, thus only reading one column per file.
Finally join all together into one data frame with do.call
and rbind
Upvotes: 0
Reputation: 99371
You can read the first line of a file via readLines(n = 1)
. To read all the first lines, use an apply loop. Then you can just put the result into a data frame.
data.frame(comment = sapply(x, readLines, n = 1))
where x
is the character vector of file names.
Upvotes: 2