有时需要按照一定字段将一个数据文件拆分为多个,
有时需要以Excel格式同时输出、保存多个数据分析结果,
可用R语言进行操作,具体做法如下:
library(readxl)
library(xlsx)
library(dplyr)
data <- read_excel("data.xlsx")
codee = unique(data$code)
# dtname1 = paste("dt",1:length(codee),sep = "")
# dtname2 = paste("dt_cor",1:length(codee),sep = "")
dtname1 = codee
dtname2 = paste(codee,"_cor",sep = "")
# for (i in c(1:length(codee))) {
# assign( paste("dt",i,sep = ""), data.frame(subset(data, data$code == codee[i])))
# }
outPath = "C:\\Users\\yangqie\\Desktop\\data" ##输出路径
out_fileName1 = sapply(dtname1,function(x){paste(x, ".xlsx", sep='')}) ##.xlsx格式
out_filePath1 = sapply(out_fileName1, function(x){paste(outPath ,x,sep='\\')}) ##输出路径名
##输出文件 按字段将一批数据分解为多批数据,并进行相应命名
for(i in 1:length(codee)){
write.xlsx(assign(dtname1[i], data.frame(subset(data, data$code == codee[i]))),
file=out_filePath1[i], row.name=T)
}
##按字段将一批数据分解为多批数据,并进行相应命名
aaa = c()
for (i in c(1:length(codee))) {
aaa[[i]] = assign(dtname1[i], data.frame(subset(data, data$code == codee[i])))
}
# for (i in c(1:length(codee))) {
# assign(paste("cor_dt",i,sep = ""), data.frame(cor(aaa[[i]][4:length(data)])))
# }
out_fileName2 = sapply(dtname2,function(x){paste(x, ".xlsx", sep='')}) ##.xlsx格式
out_filePath2 = sapply(out_fileName2, function(x){paste(outPath ,x,sep='\\')}) ##输出路径名
##同时对多批数据进行相关分析,并输出多个结果文件
for(i in 1:length(codee)){
write.xlsx(assign(dtname2[i], data.frame(cor(aaa[[i]][4:length(data)]))),
file=out_filePath2[i], row.name=T)
}
thanks