Home > Enterprise >  How to copy values between each matching line in R
How to copy values between each matching line in R

Time:10-17

I want to copy values of one df behind matching variables in another data frame. One data frame has more rows so I need the corresponding data-frame to copy to several rows. Example shown below. My goal is to get df3.

df1
id value1
1  10
1  20
2  30
2  40

df2
id value2
1  100
2  200

df3
id value1 value 2
1  10     100
1  20     100
2  30     200
2  40     200

Thank you!

CodePudding user response:

Using dplyr with left_join seems to get the output you are looking for

df1 <- data.frame(id=c(1,1,2,2),value1=c(10,20,30,40))
df2 <- data.frame(id=c(1,2),value2=c(100,200))
library(dplyr)
df3<- left_join(df1,df2)
df3

output

  id value1 value2
1  1     10    100
2  1     20    100
3  2     30    200
4  2     40    200

CodePudding user response:

A base R solution uses rep to copy the elements of value2. The argument each has the effect that it replicates all occurrences of one value before it goes to the next.

df1 <- data.frame(id = 1:4, value1 = seq(10, 40, 10))
df2 <- data.frame(value2 = c(100, 200))

df3 <- cbind(df1, value2 = rep(df2$value2, each = nrow(df1)/nrow(df2)))
df3
#>   id value1 value2
#> 1  1     10    100
#> 2  2     20    100
#> 3  3     30    200
#> 4  4     40    200

Created on 2021-10-16 by the reprex package (v2.0.1)

Created on 2021-10-16 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related