[英]R: Adding columns with value found in different dataframe
Sorry if this has been asked before. 抱歉,以前是否有人问过。 I am fairly new to R, and strugling a tad with formulating the question correctly. 我对R相当陌生,并努力地提出正确的问题。
I have two dataframes imported from a csv, looking similar to this: 我有两个从csv导入的数据框,看起来与此类似:
df1:
date time vdd temp seat volume output
... ... 1.8 25 1 ... ...
... ... 1.8 -40 0 ... ...
... ... ... ... ... ... ...
And 和
df2:
seat temp vdd noise
0 -40 1.8 5.3E-09
1 25 1.8 4.9E-09
. . . .
I want the second dataframe to work as a lookup table, to create a new column in the first dataframe, producing a result like this: 我希望第二个数据帧用作查找表,在第一个数据帧中创建一个新列,产生如下结果:
df1:
date time vdd temp seat volume output noise
... ... 1.8 25 1 ... ... 4.9E-09
... ... 1.8 -40 0 ... ... 5.3E-09
... ... ... ... ... ... ... ...
I have tried looking at merge and match, but I can't wrap my head around how to produce the result I want. 我已经尝试过寻找合并和匹配,但是我无法将注意力集中在如何产生想要的结果上。
Thanks for any help I can get. 感谢您的任何帮助。
You can easily use merge()
as you mentioned in your post. 您可以轻松地使用您在帖子中提到的merge()
。
merge(df1, df2, by=c("seat", "temp", "vdd"))
By default this will keep all records from the first data frame and only corresponding records from the second. 默认情况下,这将保留来自第一个数据帧的所有记录,仅保留来自第二个数据帧的相应记录。 To keep all records from both, use all=T
. 要同时保留所有记录,请使用all=T
Alternatively you can omit the by=
argument and it will merge on all common columns. 或者,您可以省略by=
参数,它将在所有公共列上合并。
There are several ways you could approach this, but I find this to be the easiest: 有几种方法可以解决此问题,但我发现这是最简单的方法:
install.packages("sqldf")
It lets you use SQL commands to transform data. 它使您可以使用SQL命令来转换数据。
require(sqldf)
output_table <- sqldf("select df1.*, df2.noise from df1 join df2 on df1.seat = df2.seat")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.