【发布时间】:2011-10-16 20:08:33
【问题描述】:
我正在尝试从目录中导入一系列文件并将它们中的每一个转换为一个数据框。我还想使用文件标题创建两个具有标题相关值的新列。输入文件的格式为:xx_yy.out
其中 XX 当前可以是三个值之一。 YY 当前有两个可能的值。未来这些数字还会上升。
基于 cmets 编辑解决方案(原始问题见下文)
再次编辑以反映@JoshO'Brien 的建议
filelist <- as.list(dir(pattern = ".*.out"))
for(i in filelist) {
tempdata <- read.table(i) #read the table
filelistshort <- gsub(".out$", "", i) #remove the end of the file
tempsplit <- strsplit(filelistshort, "_") #remove the underscore
xx <- sapply(tempsplit, "[", 1) #get xx
yy <- sapply(tempsplit, "[", 2) #get yy
tempdata$XX <- xx #add XX column
tempdata$YY <- yy #add YY column
assign(gsub(".out","",i), tempdata) # give the dataframe a shortened name
}
下面是原始代码,显示我想使用一些方法来获取 XX 和 YY 值,但不确定最好的方法:
我的大纲(在@romanlustrik post 之后)如下:
filelist <- as.list(dir(pattern = ".*.out"))
lapply(filelist, FUN = function(x) {
xx <- grep() or pmatch()
yy <- grep() or pmatch()
x <- data.frame(read.table(x))
x$colx <- xx
x$coly <- yy
return(x)
})
其中xx <- 和yy <- 行将是基于pmatch 或grep 的查找。我正在玩弄其中一项工作,但欢迎任何建议。
【问题讨论】: