简体   繁体   English

R-根据行匹配,使用来自另一个数据框的值填充一个数据框

[英]R - Populate one data frame with values from another dataframe, based on row matching

I'm trying to replace values in myDF1 from myDF2, where rows match for column "studyno" but the solutions I have found so far don't seem to be giving me the desired output. 我正在尝试从myDF2替换myDF1中的值,其中行与列“ studyno”相匹配,但是到目前为止我发现的解决方案似乎并没有给我想要的输出。

Below are the data.frames: 以下是data.frames:

myDF1 <- structure(list(studyno = c("J1000/9", "J1000/9", "J1000/9", "J1000/9", 
"J1000/9", "J1000/9"), date = structure(c(17123, 17127, 17135, 
17144, 17148, 17155), class = "Date"), pf_mcl = c(NA_integer_, 
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
), year = c(2016, 2016, 2016, 2016, 2016, 2016)), .Names = c("studyno", 
"date", "pf_mcl", "year"), row.names = c(NA, 6L), class = "data.frame")

myDF2 <- structure(list(studyno = c("J740/4", "J1000/9", "J895/7", "J931/6", 
"J609/1", "J941/3"), pf_mcl = c(0L, 0L, 0L, 0L, 0L, 0L)), .Names = c("studyno", 
"pf_mcl"), row.names = c(NA, 6L), class = "data.frame")

One solution I tried that seemed to work is shown below, however, I find that whatever values were in myDF1 before have been removed. 下面显示了我尝试过的一种可行的解决方案,但是,我发现myDF1中的任何值都已被删除。

myDF1$pf_mcl <- myDF2$pf_mcl[match(myDF1$studyno, myDF2$studyno)]
# Merge myDF1 & myDF2 by the "studyno", keeping all the rows in myDF1
agg_df = merge(myDF1, myDF2, "studyno", all.x=TRUE)
# Populate pf_mcl in the merged dataframe by using pf_mcl in myDF2 if it is available. Otherwise, use pf_mcl from myDF1
# is missing in myDF1
agg_df$pf_mcl = ifelse(is.na(agg_df$pf_mcl.y), agg_df$pf_mcl.x, agg_df$pf_mcl.y)
myDF1 = agg_df[, names(myDF1)]

暂无
暂无

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

相关问题 R:从一个数据框中提取行,基于列名匹配另一个数据框中的值 - R: Extract Rows from One Data Frame, Based on Column Names Matching Values from Another Data Frame 对于R中的data.frame,根据来自另一个数据帧的值从一个数据帧提取数据 - For data.frame in R, pulling data from one data frame based on values from another data frame 如何基于一列的部分与另一数据框中的值的匹配来填充R中的列 - How to fill columns in R based on matching parts of one column to values in another data frame 如何用所有列的另一个数据框中的匹配行替换一个数据框中的行 - How to replace row in one data frame with matching rows from another dataframe for all columns 根据2个匹配的列值将值从一个data.frame添加到另一个 - Adding values from one data.frame to another based on 2 matching column values 在 R 中的另一个 dataframe 中的特定位置添加一个数据框的行 - Adding row of one data frame at a specific spot in another dataframe in R 将选定列中的值和一个数据框中的匹配行覆盖到另一个数据框中,R - Overwrite values from selected columns and matching rows from one data frame into another, R 根据预定义的列集从另一个数据框中填充值 - populate values from another data frame based on predefined set of columns 根据 R 中的两个匹配条件将一个数据帧中的值添加到另一个数据帧 - Adding values from one dataframe to another based on two matching conditions in R R:根据来自另一个数据框的匹配行更新列 - R: Update column based on matching rows from another data frame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM