【问题标题】:Extract values from one table to another by matching通过匹配从一个表中提取值到另一个表
【发布时间】:2021-08-08 02:18:28
【问题描述】:

我正在匹配两个表并将主表中的值提取到另一个表中。

我有两张桌子(请看下图):

“表1”由不同日期的坐标值组成;该表有一百万行(每行代表一个坐标)和三千列(每列代表一个特定日期) “表 2”看起来与表 1 相似。但“表 2”单元格的值是“表 1”的列名。

目的:根据两个表中的“日期...”和“坐标”,将“表1”单元格中的值提取到“表2”单元格中。

创建了一个简单的循环(参见下面的代码)。但是要花太多时间才能得到结果。

table1<-data.frame(longitude=10:12,
                   latitude=20:22,
                   a=1:3,
                   b=2:4,
                   c=3:5,
                   d=4:6)
colnames(table1)[3:6]<-c("2020-01-01","2020-01-02","2020-01-03","2020-01-04")
table1
table2<-data.frame(longitude=10:12,
               latitude=20:22,
               date1=c("2020-01-02","2020-01-04","2020-01-03"),
               date2=c("2020-01-04","2020-01-02","2020-01-01"),
               date3=c("2020-01-03","2020-01-02","2020-01-04"))
table2
for(i in 1:nrow(table1)){
   w<-table2[i,-(1:2)]
   for(j in 1:length(w)){
   table2[i,j+2]<-table1[i,which(colnames(table1) %in% w[j])]
 }}
table2

如果有人可以与我分享 R 中的解决方案,我们将不胜感激。 对于具有数百万行和数千列的表

【问题讨论】:

  • 已经给出了一个例子。期待您的回答。

标签: r loops match


【解决方案1】:

这是使用lapply 的基本 R 方法 -

#columns of interest in table1
col1 <- grep('\\d+-\\d+-\\d+', names(table1), value = TRUE)
#columns of interest in table2
col2 <- grep('date\\d+', names(table2))
#Create a sequence of row numbers for table1
n <- seq(nrow(table1))

#For each column use match to get corresponding value
table2[col2] <- lapply(table2[col2], function(x) 
                       table1[col1][cbind(n, match(x, col1))])
table2

#  longitude latitude date1 date2 date3
#1        10       20     2     4     3
#2        11       21     5     3     3
#3        12       22     5     3     6

【讨论】:

  • 亲爱的 Ronak Shah,感谢您的精彩分享。它既实用又省时。对于数百万行数千列的表,只需不到一分钟即可完成。再次感谢。
【解决方案2】:

使用tidyverse

library(dplyr)
table2 %>% 
  mutate(across(starts_with('date'),
    ~ table1[cbind(match(longitude, table1$longitude), 
        match(., names(table1)))]))
  longitude latitude date1 date2 date3
1        10       20     2     4     3
2        11       21     5     3     3
3        12       22     5     3     6

【讨论】:

  • 亲爱的 akrun,非常感谢您的解决方案。它对我的情况非常有效。
猜你喜欢
  • 2014-02-16
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-29
相关资源
最近更新 更多