簡體   English   中英

從表Excel中提取列並將其合並到另一個表中

[英]Extracting columns from table Excel and merging them into another table

我有許多(數百)個Excel文檔,每個文檔約有10列和10行。

我的目標是創建包含第一列和第二列的單獨的 txt文件,然后創建包含第一列和第三列的另一個文件,依此類推...對於其余的excel文件也是如此。

有什么辦法可以在Excel中執行此操作嗎? 而是可以在R中應用批處理命令進入Excel文件(以前導出為CSV或類似類型)以生成包含成對列的單獨txt文件嗎?

這是在R中執行此操作的一種可能方法。這僅適用於一個csv文件,但可以輕松地將其適用於許多文件。

##Simulate data
write.csv(matrix(rnorm(100),ncol=10),file="test.csv",row.names=FALSE)
data1<-read.csv("test.csv")

##Create the matrix containing the columns numbers for exporting. 
##Note the code is not nice. There is a function which gives this 
##matrix immediately, but I forgot it.
rr<-numeric()
for(i in 1:9) for(j in (i+1):10) rr<-rbind(rr,c(i,j))

##Write the columns in separate files
for(i in 1:nrow(rr)) write.csv(data1[,rr[i,]],file=paste("output1_",paste(rr[i,],collapse="_"),".csv",sep=""),row.names=FALSE)

這段代碼使用一個文件名為test.csv和生產類型的文件output1_coln1_coln2.csv其中coln1coln2是列數。

對於許多文件,請將其包裝到函數中並遍歷所有csv文件。

隨着文件的循環:

fnames<-list.files(pattern = "myFile*.csv")
fnums<-as.integer(sub(".csv", "", sub("myFile", "", fnames, fixed=TRUE), fixed=TRUE))

for(i in seq_along(fnums))
{
    dta<-read.csv(fnames[i])
    #halfnumcols<-dim(dta) %/% 2
    #for(j in (seq(halfnumcols)-1))
    #{
    #   write.csv(dta[,j*2+c(1,2)], paste("resultFile", i, ".", (j+1), ".csv", sep=""))
    #}
    #EDIT: instead of neighbor pairs, run over all pairs
    numcols<-dim(dta)[2]
    apply(combn(seq(numcols), 2), 2, function(curcomb){
        write.csv(dta[,curcomb)], paste("resultFile", i, ".", curcomb[1], ".", curcomb[2], ".csv"))
    })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM