What are you actually trying to do here? For the example you give, I would just 
sample the index and apply it to both vectors:

ix <- sample(1:20, 5)
df2 <-data.frame(x=df1$x[ix], z=df1$z[ix])

(or even df2 <- df1[ix, c("x","z")] )

If it is something else, you are trying to achieve, it would seem that you rely 
on df1$x not having duplicates or you might have an assignment between 
incompatible vectors in the for loop.

-pd 

> On 20 Jan 2026, at 11.25, 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.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: [email protected]  Priv: [email protected]

______________________________________________
[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