Às 10:52 de 20/01/2026, Eric Berger escreveu:
Here is one approach with base R, starting with your first 2 lines,
then a 1-liner

df1 = data.frame(x = 1:20,
                 y = rep(letters[1:5],4),
                 w = c(rep(LETTERS[1],10), rep(LETTERS[2],10)),
                 z = rnorm(20),
                 stringsAsFactors = FALSE)
df2 = data.frame(x = sample(df1$x, 5))


df2 <- merge(df2, df1, by="x", sort=FALSE)[,c("x","z")]

HTH,
Eric


On Tue, Jan 20, 2026 at 12:25 PM Luigi Marongiu
<[email protected]> wrote:

Dear all,
this is a basic question but I could not find a specific answer online.
I have a dataframe (df1) with, in particular, an identification value
`x` and an output value `z`.
I also have another dataframe (df2) that shares `x`.
I need to assign `z` to df2 where df1$x is equal to df2$x.
What would be a straightforward way of doing this?
I can do it, but selecting one element at a time, checking the
identity of the x elements, and then assigning z. There should be a
more R way...
Thank you


```
df1 = data.frame(x = 1:20,
                 y = rep(letters[1:5],4),
                 w = c(rep(LETTERS[1],10), rep(LETTERS[2],10)),
                 z = rnorm(20),
                 stringsAsFactors = FALSE)
df2 = data.frame(x = sample(df1$x, 5))
df2$z = NA
for (i in df1$x) {
   df2$z[df2$x==i] = df1[df1$x==i,]$z
}
```

______________________________________________
[email protected] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

______________________________________________
[email protected] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Hello,

Another option is


i <- match(df2$x, df1$x)
df2$z <- df1$z[i]


or simply


df2$z <- df1$z[match(df2$x, df1$x)]


Hope this helps,

Rui Barradas

______________________________________________
[email protected] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to