我有一个具有这种信誉结构的txt文件:
“
fileName1.doc Author=Name
fileName2.doc Author=Name
fileName2.doc Author=Name
“如何在没有扩展名和作者使用扫描的情况下只保存文件名(前9个字符)?
我用:
Fnames <- scan("E:/myFiles.txt",character())发布于 2017-12-30 21:45:56
若要只获取前9个字符,请使用sep="\n"逐行扫描并使用substr(..., 1, 9)。
substr(scan("E:/myFiles.txt", what="", sep="\n"), 1, 9)您甚至可以将read.table() (在后台使用scan() )与sep="."一起使用,并获取第一列。这样,如果文件名超过9个字符,就不需要担心了。它会把它们都还回去的。
read.table("E:/myFiles.txt", sep=".", stringsAsFactors=FALSE)[[1]]使用text参数read.table()的示例如下:
read.table(text = x, sep = ".", stringsAsFactors = FALSE)[[1]]
# [1] "fileName1" "fileName2" "fileName2"数据:
x <- "fileName1.doc Author=Name
fileName2.doc Author=Name
fileName2.doc Author=Name"发布于 2017-12-31 00:29:48
下面是一个readr包的解决方案,它运行速度比基本R快10倍。将文件作为一个固定的文件读取允许我们只读取每一行的前9个字符,并利用readr::read_fwf()的性能特征。
library(readr)
rawData <- "fileName1.doc Author=Name
fileName2.doc Author=Name
fileName2.doc Author=Name
"
data <- read_fwf(rawData,fwf_widths(9,col_names="fileName"))https://stackoverflow.com/questions/48038103
复制相似问题