所以我在一个excel文件中有多个表(例如表的选项卡:s1、s2、s3(。我想创建一个函数来读取它们,并用它们重复的tabname将表格的每个选项卡附加到另一列,然后将它们组合在一起作为一个数据框架。
#####Step1读入函数中的多个工作表选项卡s1<-data.frame(ID=c(132,453,644))
s2<-data.frame(ID=c(1332,4532,6443))
s3<-data.frame(ID=c(432,643,747))
> s1
ID
1 132
2 453
3 644
> s2
ID
1 1332
2 4532
3 6443
> s3
ID
1 432
2 643
3 747
######结果步骤2s1$tabname<-c(rep('s1',nrow(s1)))
> s1
ID tabname
1 132 s1
2 453 s1
3 644 s1
s2$tabname<-c(rep('s2',nrow(s2)))
> s2
ID tabname
1 1332 s2
2 4532 s2
3 6443 s2
s3$tabname<-c(rep('s3',nrow(s3)))
> s3
ID tabname
1 432 s3
2 643 s3
3 747 s3
####我的终极目标ultimate<-rbind(s1,s2,s3)
> ultimate
ID tabname
1 132 s1
2 453 s1
3 644 s1
4 1332 s2
5 4532 s2
6 6443 s2
7 432 s3
8 643 s3
9 747 s3
####我坚持执行第2步,根据标签名称添加col,还必须对第3步进行硬编码。我的代码如下,有人能给我任何提示吗?#library("readxl")
Import<-function(Ref){
Excel.Ref<-read_xlsx("The Excel Sheet I Have.xlsx", sheet = Ref)
for (Ref in 1:length(Ref)){
Excel.Ref<-cbind(Excel.Ref,
Excel.Tab<- data.frame (Tab_name =rep(Ref,nrow(Excel.Ref))))
}
return(Excel.Ref)
print(Ref)
}
d<-c('s1','s2','s3')
Obs<-apply(d<-as.matrix(d), 1, function(x)do.call(Import, as.list(x)))
我使用readxl和tidyverse的组合来管理您想要的结果。我在我的环境中创建了一个名为test_file的文件。
##First: get all sheet names
sheets_to_read <- readxl::excel_sheets("test_file.xlsx")
##Second: read all sheets, add tabname, and then bind rows
x <- bind_rows(lapply(1:length(sheets_to_read),
function(i)readxl::read_excel("test_file.xlsx",
sheet = sheets_to_read[i]) %>%
mutate(tabname = sheets_to_read[i])))
x
这里有一个简单的dplyr
解决方案:
Import <- function(xlsxfile,col_names){
# get names of sheets in input xlsxfile
sheets <- readxl::excel_sheets(xlsxfile)
# sheets as list
l <- lapply(sheets, readxl::read_xlsx, path=xlsxfile, col_names=col_names)
# sheets as data.frame
dplyr::bind_rows(l,.id="tabname")
}
Import(xlsxfile,col_names="ID")
# A tibble: 9 x 2
tabname ID
<chr> <dbl>
2 1 132
3 1 453
4 1 644
6 2 1332
7 2 4532
8 2 6443
10 3 432
11 3 643
12 3 747
使用read_xlsx()
的col_names
参数可以指定具有选项卡名称的列的名称。
使用bind_rows()
将data.frames
的列表绑定到单个data.frame
中,以跟踪名称由.id
参数给定的新列中的原始data.frame
。