我正在使用 R 将一些大型文本文件读入数据库,但它们包含数据库软件的非法字段名称。大型文本文件的列名仅在第一行中 - 是否可以仅编辑第一行而不循环遍历文件中的每一行(这似乎浪费资源)?
这是我尝试对一些示例数据执行的操作的两个示例。第一个将所有内容读入内存 - 因此这不适用于我的大型数据表。第二个可以工作,但速度很慢,因为它处理文件中的每一行。
我认为解决方案跨平台工作很重要and不需要安装外部软件(除了 R 包),只是因为我将与其他人共享此脚本,并且不想要求他们执行不必要的步骤。我正在寻找最快的方法来做到这一点仅在 R 内 :)
# create two temporary files
tf <- tempfile() ; tf2 <- tempfile()
# write the mtcars data table to a file on the disk
write.csv( mtcars , tf )
# look at the first three lines
readLines( tf , n = 3 )
# read in the entire table
z <- readLines( tf )
# make the only substitution i care about
z[1] <- gsub( 'disp' , 'newvar' , z[1] )
# write the entire table back out to the table
writeLines( z , tf2 )
# confirm the replacement
readLines( tf2 , 2 )
# done!
# # # # # # # OR
# blank out the output file
file.remove( tf2 )
# create a file connection to the text file
incon <- file( tf , "r" )
# create a second file connection to the secondary temporary file
outcon <- file( tf2 , "w" )
# read in one line at a time
while( length( one.line <- readLines( incon , 1 ) ) > 0 ){
# make the substitution on every line
one.line <- gsub( 'disp' , 'newvar' , one.line )
# write each line to the second temporary file
writeLines( one.line , outcon )
}
# close the connections
close( incon ) ; close( outcon )
# confirm the replacement
readLines( tf2 , 2 )
# done!
您为此使用了错误的工具。请改用一些命令行工具。例如。使用sed
, 类似sed -i '1 s/disp/newvar/' file
应该做。如果你have to在 R 中执行此操作,使用
filename = 'myfile'
scan(pipe(paste("sed -i '1 s/disp/newvar/' ", filename, sep = "")))
这是一个特定于 Windows 的版本:
filename = 'myfile'
tf1 = tempfile()
tf2 = tempfile()
# read header, modify and write to file
header = readLines(filename, n = 1)
header = gsub('disp', 'newvar', header)
writeLines(header, tf1)
# cut the rest of the file to a separate file
scan(pipe(paste("more ", filename, " +1 > ", tf2)))
# append the two bits together
file.append(tf1, tf2)
# tf1 now has what you want
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)