1

I am currently experiencing perpetual issues with object selection within loops in R. I am fairly convinced that this is a common problem but I cannot seem to find the answer so here I am...

Here's a practical example of a problem I have: I have a dataframe as source with a series of variables named sequentially (X1,X2,X3,X4, and so on). I am looking to create a function which takes the data as source matches it to another dataset to create a new, combined dataset.

The number of variables will vary. I want to pass my function a parameter which tells it how many variables I have, and the function needs to adjust the number of times it will run the code accordingly. This seems like a task for a for loop, but again there doesn't appear to be an easy way for that selection and recreation of variables within a loop.

Here's the code I need to repeat:

new1$X1 <- data$X1[match(new1$matf1, data$rowID)]
new1$X2 <- data$X2[match(new1$matf1, data$rowID)]
new1$X3 <- data$X3[match(new1$matf1, data$rowID)]
new1$X4 <- data$X4[match(new1$matf1, data$rowID)]
new1$X5 <- data$X5[match(new1$matf1, data$rowID)]
(...)
return(new1)

I've attempted something like this:

for(i in 1:5) {
  new1$Xi <- assign(paste0("X", i)), as.vector(paste0("data$X",i)[match(new1$matf1, data$rowID)])
}    

without success.

Thank you for your help!

  • I'm having a hard time seeing how this is different that performing a join between `new1` and `data` and matching on `new1$matf1 = data$rowid`. – zack Jul 26 '18 at 16:58
  • Seems like you want `merge(new1, data, by.x = "matf1", by.y = "rowID")`? Possible duplicate [How to join (merge) data in R?](https://stackoverflow.com/q/1299871/903061) – Gregor Thomas Jul 26 '18 at 17:22

1 Answers1

0

You can try this simple way, however a join would be more efficient:

vals <- paste0('X',1:5)

for(i in vals){
    new1[[i]] <- data[[i]][match(new1$matf1, data$rowID)]
}
YOLO
  • 20,181
  • 5
  • 20
  • 40