I have two dataframes.
X1 is
size count
37 1.181
38 0.421
39 0.054
and X2 is
size v1 v1
37 1 5
... ... ...
37 1 5
38 3 3
... ... ...
38 3 3
39 5 6
... ... ...
39 5 6
Dataframe X2 is a large panel basically. I want to create a 3rd column, v3, in X2, such that it takes the value of count from X1 if size matches.
How is this possible?
You can join the two datasets together like this:
library(dplyr)
left_join(X2, X1, by="size")
Example with the Iris dataset:
I2<-data.frame(Species=c("setosa", "versicolor", "virginica"),
myData=c(1,2,3))
left_join(iris, I2, by="Species")
This can be accomplished via a left_join()
from the dplyr
package.
library(dplyr)
x1 <- tribble(~size, ~count,
37, 1.181,
38, 0.421,
39, 0.054
)
x2 <- tribble(~size, ~v1, ~v2,
37, 1, 5,
37, 1, 5,
38, 3, 3,
38, 3, 3,
39, 5, 6,
39, 5, 6
)
left_join(x2, x1, by = "size")
Produces:
# size v1 v2 count
# <dbl> <dbl> <dbl> <dbl>
# 1 37 1 5 1.18
# 2 37 1 5 1.18
# 3 38 3 3 0.421
# 4 38 3 3 0.421
# 5 39 5 6 0.054
# 6 39 5 6 0.054
The base R function merge
would get you there as well.
merge(x2, x1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.