简体   繁体   English

通过匹配两个数据框中的每一行中的值来填充列值

[英]Fill column values by matching values in each row in two dataframe

It's a little bit hard to describe my problem. 描述我的问题有点困难。 Suppose I have two data.frame and I have to fill column values by matching values in each row. 假设我有两个data.frame,我必须通过匹配每行中的值来填充列值。

data1
         date  lat   long      ele  
1 16-JAN-1995 36.2 -113.8       NA
2 16-JAN-1995 33.8 -113.8       NA
3 16-JAN-1995 31.2 -113.8       NA
4 16-JAN-1995 28.8 -113.8       NA
5 16-JAN-1995 26.2 -113.8       NA
6 16-JAN-1995 23.8 -113.8       NA

data2
   lat   long     ele
1 36.2 -113.8 1526.25
2 33.8 -113.8  612.94
3 31.2 -113.8  328.62
4 28.8 -113.8  367.81
5 26.2 -113.8   58.50
6 23.8 -113.8    0.00

Data1 has around 40k rows, and data2 has around 500. Data1大约有4万行,data2大约有500行。

I want 我想要

if data1$lat == data2$lat and data1$long == data2$long , then data1$ele == data2$ele . 如果data1$lat == data2$latdata1$long == data2$long ,则data1$ele == data2$ele

I also want to check the lat and long values row by row of the 2 dataframes to ensure the long&lat value matches. 我还想逐行检查2个数据帧的经纬度值,以确保经纬度值匹配。

I have tried using data.table() and merge(), but none of them seems to be working... Any ideas? 我试过使用data.table()和merge(),但它们似乎都不起作用...有什么想法吗?

Simple solution in base R: 基本R中的简单解决方案:

indices <- df1$lat == df2$lat & df1$long == df2$long

df1$ele[indices] <- df2$ele[indices]

Another way to go about it, via @Roman Lustrik's suggestion to concatenate. 通过@Roman Lustrik的建议进行串联的另一种解决方法。 Also in base R. 同样在基数R中。

df1$ele <- df2[match(paste(df1$lat,df1$long),paste(df2$lat,df2$long)),"ele"]

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

相关问题 通过匹配列名称中每一行中的值来填充列值 - Fill column values by matching value in each row on column names 在R中填充数据框列重复行值 - Fill dataframe column repeating row values in r 使用另一数据框的一行中的值替换一个数据框的一列中的所有值(按行名和列名匹配) - Replace all values in a column of one dataframe using values in a row of another dataframe (matching by row name and column name) R - 将数据框列中的值与另一个数据帧行名称匹配 - R - matching values in a dataframe column to another dataframes row names 通过将向量的值与列名匹配来填充数据帧 - Fill a dataframe by matching the values of a vector with colnames 如何基于匹配R中的其他列的行值来填充列的值 - How do I fill in values for columns based on matching few other column's row values in R 通过跨两个数据框匹配值来求和 - Sum values by matching values across two dataframe 使用另一个数据帧的行中的值替换一个数据帧的列中的所有值(按行名称和列名称匹配),替换为字符 - Replace all values in column of one dataframe using values in row of another dataframe (matching by row name&column name), replacement is characters 按列值对数据框中的行值进行排序 - sorting row values in dataframe by column values 按条件填写 dataframe 列中的空值 - Fill in empty values in column of dataframe by condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM