1

I want to simplify my current method of replacing column values of a dataframe with a vector. I've provided a reproducible answer below with my solution using base R. A simplified version contains just one data frame and with multiple dataframes, i'm forced to use a for loop due to my bad solution.

How can I simplify my approach?

# Simplified version
Df <- data.frame(a = c(1,2,3),
           b = c(4,5,6),
           c = c(7,8,9))

l <- list(c(11,22,33),
          c(44,55,66))

letters <- c("a","b")

Df[letters] <- l


# Multiple data frames
Df1 <- list(data.frame(a = c(1,2,3),
                       b = c(4,5,6),
                       c = c(7,8,9)),
            data.frame(a = c(101,102,103),
                       b = c(104,105,106),
                       c = c(107,108,109)))
l <- list( list(c(11,22,33), c(44,55,66)),
           list(c(111,222,333), c(444,555,666)) )

letters <- c("a","b")

for(i in 1:length(Df1)){

  Df1[[i]][letters] <- l[[i]]

}

1 Answer 1

2

Here is an option with map2

library(purrr)
library(dplyr)
map2(Df1, l, ~ {.x[letters] <- .y; .x})

Or with inset from magrittr

library(magrittr)
map2(Df1, l, ~  inset(.x, letters, value = .y))

or in a chain

map2(Df1, l, ~ .x %>% 
                 select(-one_of(letters)) %>% 
                 bind_cols(.y %>% 
                               set_names(letters)) %>% 
                 select(names(.x)))

Or in base R

Map(function(x, y) {x[letters] <- y;x},  Df1, l)
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you for your answer. This seems very complicated when compared to my for loop. For readability, would your solution be considered a better approach/easier to read for an experienced R user?
@Ali You asked for a solution with dplyr. If it is okay for a base R, then I can change to more simpler ways
I think that would be more appropriate as I assumed using dplyr would simplify this. I’ll change my question accordingly
@Ali Thanks. I changed the code. Now, it is one-liner, but I used the earlier code so that it would be in a chain instead of wrapping within {}
much much appreciated for this advice. I’ll take this all into account and hopefully next time will be a more complex question for you :) thank you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.