我在这里有一个脚本,在某一列中得到一个数字是很好的。现在我不仅要收集目录中每个文件的第一张,而且要收集每个文件的每一张。
现在,.csv文件R已经写好了2列,列A是文件名,B是抓取的数字R。
我应该对下面的脚本添加哪些修改,以使csv输出显示3列,A是文件名,B是单张名,C是数字?
require(xlsx)
#setwd
setwd("D:\\Transferred Files\\")
files <- (Sys.glob("*.xls"))
f<-length(files)
DF <- data.frame(txt=rep("", f),num=rep(NA, f),stringsAsFactors=FALSE)
# files loop
for(i in 1:f)
{
A<-read.xlsx(file=files[i],1,startColumn=1, endColumn=20, startRow=1, endRow=60)
#Find price
B<-as.data.frame.matrix(A)
P<-B[which(apply(B, 1, function(x) any(grepl("P", x)))),which(apply(B, 2, function(x) any(grepl("P",
x))))+6]
#fill price DF
DF[i, ] <-c(files[i],P)
}
write.csv(DF, "prices.csv", row.names=FALSE)我试过XLconnet,但实际上不能让它变成这样。
发布于 2015-05-22 17:42:13
您有一个良好的开端,但您正在询问如何将文件中的工作表添加到循环中。如果您阅读?read.xlsx,您将在代码中看到两个正在修饰的参数(嗯,使用一个参数,忽略另一个参数):
Usage:
read.xlsx(file, sheetIndex, sheetName=NULL, rowIndex=NULL,
startRow=NULL, endRow=NULL, colIndex=NULL,
as.data.frame=TRUE, header=TRUE, colClasses=NA,
keepFormulas=FALSE, encoding="unknown", ...)
Arguments:
file: the path to the file to read.
sheetIndex: a number representing the sheet index in the workbook.
sheetName: a character string with the sheet name.你只需要提供两个中的一个。
您可能会问:“我怎么知道一个工作表中有多少张工作表?”(对于sheetIndex)甚至“工作表名是什么?”(用于sheetName)。?getSheets到救援:
Usage:
getSheets(wb)
Arguments:
wb: a workbook object as returned by 'createWorksheet' or
'loadWorksheet'.
Value:
'getSheets' returns a list of java object references each pointing
to an worksheet. The list is named with the sheet names.为了获得工作表名,您需要使用loadWorkbook(file)而不是read.xlsx,但是阅读一下手册将提供您需要切换的信息。(您可以使用类似于getSheets(loadWorkbook(file))的东西,但根据我的经验,无论自动关闭,我都尽量避免在同一个脚本中多次打开同一个文件。)
作为另一种选择,Hadley的readxl包在其简单性、速度和稳定性方面显示出了希望。它有excel_sheets()和read_excel(),可以满足您的需要。(事实上,这就是它所拥有的.简单就是“好东西(Tm)”)。
编辑
library(XLConnect)
## Loading required package: XLConnectJars
## XLConnect 0.2-11 by Mirai Solutions GmbH [aut],
## Martin Studer [cre],
## The Apache Software Foundation [ctb, cph] (Apache POI, Apache Commons
## Codec),
## Stephen Colebourne [ctb, cph] (Joda-Time Java library)
## http://www.mirai-solutions.com ,
## http://miraisolutions.wordpress.com
## Attaching package: 'XLConnect'
## The following objects are masked from 'package:xlsx':
## createFreezePane, createSheet, createSplitPane, getCellStyle, getSheets, loadWorkbook, removeSheet, saveWorkbook, setCellStyle, setColumnWidth, setRowHeight
wb1 <- loadWorkbook('Book1.xlsx')
shts1 <- getSheets(wb1)
shts1
## [1] "Orig" "Sheet2" "Sheet8" "Sheet3" "Sheet4" "Sheet5" "Sheet6" "Sheet7"
for (ws in shts1) {
message(ws) # just announcing myself
dat <- readWorksheet(wb1, ws)
message(paste(dim(dat), collapse=' x ')) # do something meaningful, not this
}
## Orig
## 128 x 11
## Sheet2
## 128 x 11
## Sheet8
## 128 x 19
## Sheet3
## 17 x 11
## Sheet4
## 128 x 11
## Sheet5
## 128 x 11
## Sheet6
## 128 x 11
## Sheet7
## 128 x 11编辑#2
作为一个更详细的迭代示例:
library(XLConnect)
for (fn in list.files(pattern="*.xlsx")) {
message('Opening: ', fn)
wb <- loadWorkbook(fn)
shts <- getSheets(wb)
message(sprintf(' %d Sheets: %s', length(shts),
paste(shts, collapse=', ')))
for (sh in shts) {
dat <- readWorksheet(wb, sh)
## do something meaningful with the data
}
}我不太清楚您对代码做了什么(因为您从未说过包含在任何电子表格中的内容),但另一种方法(我将用它来代替前面的双for示例)是将所有内容都包含在列表中:
dat <- sapply(list.files(pattern='*.xlsx'), function(fn) {
wb <- loadWorkbook(fn)
sapply(getSheets(wb), function(sh) readWorksheet(wb, sh))
})
str(dat, list.len=2)
## List of 4
## $ Book1.xlsx:List of 8
## ..$ Orig :'data.frame': 128 obs. of 11 variables:
## .. ..$ i : num [1:128] 1 2 3 4 5 6 7 8 9 10 ...
## .. ..$ x : num [1:128] 1606527 7484 437881 1601729 1341668 ...
## .. .. [list output truncated]
## ..$ Sheet2:'data.frame': 128 obs. of 11 variables:
## .. ..$ i : num [1:128] 1 2 3 4 5 6 7 8 9 10 ...
## .. ..$ x : num [1:128] 1606527 7484 437881 1601729 1341668 ...
## .. .. [list output truncated]
## .. [list output truncated]
## $ Book2.xlsx:List of 8
## ..$ Orig :'data.frame': 128 obs. of 11 variables:
## .. ..$ i : num [1:128] 1 2 3 4 5 6 7 8 9 10 ...
## .. ..$ x : num [1:128] 1606527 7484 437881 1601729 1341668 ...
## .. .. [list output truncated]
## ..$ Sheet2:'data.frame': 128 obs. of 11 variables:
## .. ..$ i : num [1:128] 1 2 3 4 5 6 7 8 9 10 ...
## .. ..$ x : num [1:128] 1606527 7484 437881 1601729 1341668 ...
## .. .. [list output truncated]
## .. [list output truncated]
## [list output truncated]如果您不关心区分特定工作表来自哪个工作簿--然后简化数据处理--那么您可以将嵌套的列表“平整”成一个列表:
flatdat <- unlist(dat, recur=FALSE)
str(flatdat, list.len=3)
## List of 555
## $ Book1.xlsx.Orig :'data.frame': 128 obs. of 11 variables:
## ..$ i : num [1:128] 1 2 3 4 5 6 7 8 9 10 ...
## ..$ x : num [1:128] 1606527 7484 437881 1601729 1341668 ...
## ..$ c1 : num [1:128] 1 1 1 1 1 1 1 1 1 1 ...
## .. [list output truncated]
## $ Book1.xlsx.Sheet2:'data.frame': 128 obs. of 11 variables:
## ..$ i : num [1:128] 1 2 3 4 5 6 7 8 9 10 ...
## ..$ x : num [1:128] 1606527 7484 437881 1601729 1341668 ...
## ..$ c1 : num [1:128] 1 1 1 1 1 1 1 1 1 1 ...
## .. [list output truncated]
## $ Book1.xlsx.Sheet8:'data.frame': 128 obs. of 19 variables:
## ..$ i : num [1:128] 1 2 3 4 5 6 7 8 9 10 ...
## ..$ x : num [1:128] 1606527 7484 437881 1601729 1341668 ...
## ..$ c1 : num [1:128] 1 1 1 1 1 1 1 1 1 1 ...
## .. [list output truncated]
## [list output truncated]现在,处理您的数据可能更简单。查找“P”的代码有一点缺陷,因为您将data.frame分配给另一个data.frame中的一个单元格,这通常是皱眉反对的。
这可能会给你带来另一个问题。为此,我强烈建议您提供一个better detailed问题,包括样例工作表的外观和预期输出的样子。
https://stackoverflow.com/questions/30402461
复制相似问题