通过匹配ID和列名称来检索data.frame的值 [英] Retrieve values of the data.frame by matching ID and column name
本文介绍了通过匹配ID和列名称来检索data.frame的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为 df1
的数据框,其中有四列(即 id
, s
,日期
和值
)。值列为空,我想使用另一个名为 df2
的数据框填充它。 df2
填充有 id
列和其他许多使用其所属日期命名的列。我需要做的是在 df2
中找到相应的 df1 $ value
值,其中日期和ID号都匹配。
I have a dataframe named df1
which has four columns (i.e. id
, s
, date
and value
). The value column is empty and I want to fill it using a second dataframe that is named df2
. df2
is filled with id
column and many other columns that are named using dates which they belong. All I need is to find corresponding values of df1$value
in df2
, where both dates and id numbers are matching.
示例数据:
set.seed(123)
#df1
df1 <- data.frame(id = 1:100,
s = runif(100,100,1000),
date = sample(seq(as.Date('1999/01/01'), as.Date('2001/01/01'), by="day"), 100),
value = NA)
#df2
df2 <- data.frame(matrix(runif(80000,1,100), ncol=800, nrow=100))[-1]
names(df2) <- seq(as.Date("1999-01-01"),as.Date("2002-12-31"),1)[c(1:799)]
df2 <- cbind(id = 1:100, df2)
推荐答案
一种方法是转换 df2
转换为长格式,使用 gather
然后执行 left_join
One way is to convert df2
into long format using gather
and then do left_join
library(dplyr)
library(tidyr)
df1 %>%
left_join(df2 %>%
gather(date, value, -id) %>%
mutate(date = as.Date(date)), by = c("id", "date"))
# id s date value
#1 1 359 2000-03-15 48.32
#2 2 809 1999-09-01 62.16
#3 3 468 1999-12-23 16.41
#4 4 895 2000-11-26 32.70
#5 5 946 1999-12-18 5.84
#6 6 141 2000-10-09 74.65
#7 7 575 2000-10-25 9.22
#8 8 903 2000-03-17 6.46
#9 9 596 1999-10-25 73.48
#10 10 511 1999-04-17 62.43
#...
数据
set.seed(123)
df1 <- data.frame(id = 1:100,
s = runif(100,100,1000),
date = sample(seq(as.Date('1999/01/01'), as.Date('2001/01/01'), by="day"), 100))
df2 <- data.frame(matrix(runif(80000,1,100), ncol=800, nrow=100))[-1]
names(df2) <- seq(as.Date("1999-01-01"),as.Date("2002-12-31"),1)[c(1:799)]
df2 <- cbind(id = 1:100, df2)
这篇关于通过匹配ID和列名称来检索data.frame的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文