简体   繁体   中英

Replacing values of a dataframe column with a vector

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]]

}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM