简体   繁体   中英

Using readLines for multiple files in R

My question is similar to the topic, I would like to load two files at once. I know I can use the function list.files. However, I do not know how to apply it correctly so that my program will work. I would also like to ask how can I make two frames of data for each loaded file. Below is the look of my code (for one file):

txt <- stri_read_lines("script.R")
txt <- txt[txt != ""]
r1 <- strsplit(txt, "")
r2 <- lengths(r1)
r3 <- unlist(r1)
r4 <- rep(
  seq_along(r1),
  r2
)
r5<- unlist(
  lapply(r2, seq_len)
)
TD <- data.frame(
  signs = r3,
  rows= r4,
  columns= r5
)
TD

You can define your code as a function and then use it inside lapply or sapply :

readfiles <- function(docname){
  txt <- stri_read_lines(docname)
  txt <- txt[txt != ""]
  r1 <- strsplit(txt, "")
  r2 <- lengths(r1)
  r3 <- unlist(r1)
  r4 <- rep(seq_along(r1), r2)
  r5 <- unlist(lapply(r2, seq_len))
  TD <- data.frame(
          signs=r3,
          rows=r4,
          columns=r5)
  return(TD)
}

docnames <- list.files(pattern="*.R")
yourdocs <- lapply(docnames, readfiles)
list2env(yourdocs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM