简体   繁体   English

如何用R合并具有不同行的列

[英]How to combine columns with different rows with R

I have several excel files and need to combine the fourth column of each table. 我有几个Excel文件,需要合并每个表的第四列。 However, the rows of the table are different. 但是,表的行是不同的。 Some of them have 7 rows but some of them have 5 or 6 rows. 其中一些具有7行,但其中一些具有5或6行。 Here are my data descriptions. 这是我的数据描述。

在此处输入图片说明

As you can see, there are three excel files and I need to merge the fourth column. 如您所见,有三个Excel文件,我需要合并第四列。 One of them has 7 rows while the other two has 5 and 6 rows. 其中一个具有7行,而另外两个具有5和6行。 I try to use a loop reading all files inside a folder and then use "merge" to do this. 我尝试使用循环读取文件夹中的所有文件,然后使用“合并”执行此操作。

Here is my code. 这是我的代码。

rm(list=ls())
updir = "D:/STAR/MergeResults/Rtest"
library(readxl)

setwd(updir)    #set up the working dictionary

outfile <- ""   #first define an empty variable

file_list <- list.files(pattern = NULL) 

for (i in 1:length(file_list)) {
   file <- read_excel(file_list[i],col_names = TRUE) 
   variable <- file[,4]
   outfile <-merge(outfile,variable)
}

Can anyone help me merge these columns with different rows? 谁能帮助我将这些列与不同的行合并?

I changed the way outfile is initialized so that it is an empty vector. 我更改了outfile的初始化方式,使其为空向量。 You can combine vectors using the c() function. 您可以使用c()函数组合向量。 The rest of your code can remain the same. 您的其余代码可以保持不变。

cols <- apply(file_list,function(x) {
  read_excel(file_list[i],col_names = TRUE)[,4]
})

max_length <- max(sapply(cols,length))

outfile <- data.frame(x = 1:max_length)

for(v in cols) {
  vmod <- c(v,rep(NA,max_length - length(v)))
  outfile <- cbind(outfile,vmod)
}

outfile <- outfile[,-1]

write to excel: 写给excel:

library(openxlsx)

write.xlsx(outfile, file = "NewFile.xlsx", colNames = TRUE,rowNames = FALSE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM