[英]How to convert .txt to .csv file in R
我在这里找到了这段代码,它可以将“.txt”转换为“.csv”,但文件没有分成列,很确定这里有一个简单的修复或添加行,但我没有找到它。 r 仍然是新手并正在努力,因此感谢您提供任何帮助或指导。
编辑:该文件包含以下入侵植物列表:
Header:有毒杂草清单。
'(a) Abrus precatorius - 念珠豌豆'
'(b) Aeginetia spp。 – 紫荆花'
'(c) Ageratina adenophora - crofton weed'
'(d) Alectra spp。 – 阿莱克特拉 '
所以我想把所有的部分,即属、种和通用名,放在一个单独的列中。 如果可能,删除字母“(a)”和“-”分隔连字符。
filelist = list.files(pattern = ".txt")
for (i in 1:length(filelist)) {
input<-filelist[i]
output <- paste0(gsub("\\.txt$", "", input), ".csv")
print(paste("Processing the file:", input))
data = read.delim(input, header = TRUE)
write.table(data, file=output, sep=",", col.names=TRUE, row.names=FALSE)
}
如果您的常用名称包含三个或更多单词,则需要进行调整,但这是一般的想法:
path <- "C:\\Your File Path Here\\"
file <- paste0(path, "WeedList.txt")
DT <- read.delim(file, header = FALSE, sep = " ")
DT <- DT[-c(1),-c(1,4,7)]
colnames(DT) <- c("Genus", "Species", "CommonName", "CommonName2")
DT$CommonName <- gsub("'", "", DT$CommonName)
DT$CommonName2 <- gsub("'", "", DT$CommonName2)
DT$CommonName <- paste(DT$CommonName, DT$CommonName2, sep = " ")
DT <- DT[,-c(4)]
write.csv(DT, paste0(path, "WeedList.csv"), row.names = FALSE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.