我正忙于匹配两个表,并从主表中提取值到另一个表中。
我有两个表(请看下图):
“表1”由不同日期的坐标值组成;该表有一百万行(每行代表一个坐标)和三千列(每列代表一个特定日期)。“表2”看起来与表1相似。但“表2”单元格的值是“表1”的列名。
目的:根据“日期...”将“表1”单元格中的值提取到“表2”单元格中。和在两个表中的"coordinate“。
创建了一个简单的循环(参见下面的代码)。但它需要太多的时间才能得到结果。
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中的解决方案,我将不胜感激。对于具有数百万行和数千列的表
发布于 2021-08-07 05:16:07
下面是一个使用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
发布于 2021-08-07 10:18:28
使用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
https://stackoverflow.com/questions/68691945
复制相似问题