【问题标题】:R Combining files with different number of rows and columnsR组合具有不同行数和列数的文件
【发布时间】:2018-08-01 21:39:31
【问题描述】:

有谁知道如何使用 R 组合/连接具有不同行数和列数的文件?

谢谢

【问题讨论】:

标签: r


【解决方案1】:

您应该使用merge,但在此之前您需要使用它来将其读取到内存中,例如read.csv。假设您加载了数据。见下文:

# simulation of data to be merged
set.seed(123)
x <- data.frame(id = letters[1:10], valx = rnorm(10))
dim(x)
# [1] 10  2
# 10 rows, 2 columns

y <- data.frame(id = sample(letters[1:10], 5), valy = rnorm(5), valz = LETTERS[3:7]) 
dim(y)
# [1] 5 3
# 5 rows, 3 columns

merge(x, y, by = "id", all.x = TRUE)

数据框x

   id        valx
1   a -0.56047565
2   b -0.23017749
3   c  1.55870831
4   d  0.07050839
5   e  0.12928774
6   f  1.71506499
7   g  0.46091621
8   h -1.26506123
9   i -0.68685285
10  j -0.44566197

数据框y

   id        valx
1   a -0.56047565
2   b -0.23017749
3   c  1.55870831
4   d  0.07050839
5   e  0.12928774
6   f  1.71506499
7   g  0.46091621
8   h -1.26506123
9   i -0.68685285
10  j -0.44566197

合并的data.frame(第一个数据帧x中的所有行都被保留):

   id        valx       valy valz
1   a -0.56047565         NA <NA>
2   b -0.23017749         NA <NA>
3   c  1.55870831         NA <NA>
4   d  0.07050839  0.8255398    G
5   e  0.12928774         NA <NA>
6   f  1.71506499 -1.0488931    E
7   g  0.46091621  0.2382129    D
8   h -1.26506123         NA <NA>
9   i -0.68685285  0.5490967    C
10  j -0.44566197  1.2947633    F

【讨论】:

  • 谢谢。在我合并之前,我必须读取数据并且我得到错误:输入中没有可用的行。之前请看代码
  • for (i in 1:length(fileL)) { for (j in 1:length(fileL[[i]])) { # 获取并读取文件 if (j==1) { newFile
  • 使用tryCatch。您正在加载的位置缺少 fileL 列表中的某些文件。由于 cmets 太紧,最好再发布一个问题for (i in 1:length(fileL)) { for (j in 1:length(fileL[[i]])) { # fetch and read files tryCatch( { if (j==1) { trnewFile &lt;- read.delim(paste(dataFnsDir, fileL[[i]][j], sep="/"), as.is=T) print(fileL[[i]][j]) } else { newFile&lt;- dplyr::rbind_rows(newFile, read.delim(paste(dataFnsDir, fileL[[i]][j], sep="/"), as.is=T)) } }, error=function(e) NULL) } }
  • 如果没有可重现的示例,很难提供帮助。请看这里How to make greate reproducible example
猜你喜欢
  • 1970-01-01
  • 2022-11-24
  • 2020-06-20
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 2022-01-13
相关资源
最近更新 更多