'How can I add a column from one dataframe to another with certain conditions? [duplicate]
I have 2 dataframes and I am using R:
| Van | Route | Time |
|---|---|---|
| U31 | 23452 | 8:00 |
| U72 | 13422 | 7:00 |
| U98 | 53622 | 8:00 |
| U24 | 16622 | 8:00 |
| U75 | 76422 | 6:00 |
| U45 | 98422 | 8:00 |
| U27 | 46422 | 9:00 |
| Van | Seats |
|---|---|
| U27 | 20 |
| U72 | 22 |
| U24 | 13 |
| U98 | 16 |
| U75 | 22 |
| U45 | 12 |
| U31 | 22 |
the problem here is that both data frames are ordered differently and I would like to add the column of "Seats" to my first DF.
This is the result I want:
| Van | Route | Time | Seats |
|---|---|---|---|
| U31 | 23452 | 8:00 | 22 |
| U72 | 13422 | 7:00 | 22 |
| U98 | 53622 | 8:00 | 16 |
| U24 | 16622 | 8:00 | 13 |
| U75 | 76422 | 6:00 | 22 |
| U45 | 98422 | 8:00 | 12 |
| U27 | 46422 | 9:00 | 20 |
So I would like to basically add this column with the condition that DF1$Vans = DF2$Vans!!!
Thanks in advance :))
Solution 1:[1]
# set as data.table
lapply(list(df1, df2), \(i) setDT(i))
# join
df2[df1
, on=.(Vans)
, mget(c("i.Van", "x.Seats"))
]
# assuming df1 has columns "Van", Route", "Time" as OP has not specified
Solution 2:[2]
Perform a simple merge:
newdf = merge(df1, df2, by="Van")
If df2 includes more columns, subset df2 to the desired column and column used to merge:
newdf = merge(df1, df2[,c("Van","Seats")], by="Van")
Solution 3:[3]
You can do this:
library(dplyr)
left_join(df1, df2[,c("Van","Seats")], by = "Van")
df2[,c("Van","Seats")] subsets df2 on two columns: Van, which is the column df1 and df2have in common and based on which the join can be performed, as well as Seats, the column you want to add to df1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
