首页 > 解决方案 > 什么是 R 中 scan() 函数的替代方法,它不仅适用于文件

问题描述

我必须阅读位于同一文件夹中的以 hello 开头的文本文件列表。我必须在每个字母后删除句点,因为我只想使用句点作为分隔符。

例如,如果一行文本看起来像这样:“apple. 10.”</p>

我删除了同一行上的句点以获得以下结果:“apple 10”。</p>

这是我的代码的一瞥。

 files0 <- list.files(path=maindir,pattern="hello",full.names=F,recursive=T,
 include.dirs=T)

下一个循环不是很有效,因为我必须创建临时文本文件才能使用 scan() 函数。

 ############### First step

for(a in 1:length(files0)){ #start of the loop going through 
# every files0

        read <- readLines(paste(maindir,files0[a],sep="/")) #read each line

        hello <- gsub("(\\D+)\\.","\\1", lec) #remove every period after a letter

        write.table(mod,file=paste(maindir,paste("temporary",files0[a],sep="_"),sep="/"),
        sep =     ";",col.names = T,row.names = F,quote = FALSE) 
        #create new temporary files without the period  after a letter

} #end of the loop

 ##################Second step

   files <- list.files(path=maindir,pattern="temporary",full.names=F,
   recursive=T,include.dirs=T)

   for(b in 1:length(files)){ #start of the loop going through every files

           hola <- scan(files[b],character(), sep=".") #read every files and 
           # use period as delimiters
   } #end of the loop

我想在 R 中找到 scan() 函数的替代方法,因为我不必创建临时文件。另外,我希望能够直接使用原始文件(files0)而不修改它们。

例如,我尝试了 strsplit() 函数,但它没有正确地使用句点分隔我的文本文件。

谢谢您的帮助。

标签: rsplitdelimiter

解决方案


我找到了一个替代方案。

for(a in 1:length(files0)){ #start of the loop going through 
# every files0

    read <- readLines(paste(maindir,files0[a],sep="/")) #read each line

    hello <- gsub("(\\D+)\\.","\\1", lec) #remove every period after a letter

hello1 <- unlist(strsplit(hello, "[.]"))

} #end of the loop

我只需要使用函数 unlist(strsplit())。


推荐阅读