简体   繁体   English

在 R 中对多个文件使用 readLines

[英]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.我知道我可以使用函数 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 :您可以将代码定义为函数,然后在lapplysapply使用它:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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