Skip to content

Instantly share code, notes, and snippets.

@padpadpadpad
Last active September 4, 2017 13:29
Show Gist options
  • Save padpadpadpad/f5d9ad112b882b62a4cd79dc0b755b06 to your computer and use it in GitHub Desktop.
Save padpadpadpad/f5d9ad112b882b62a4cd79dc0b755b06 to your computer and use it in GitHub Desktop.
example using mutate_at() and base R to edit multiple columns indexed from another data frame
# load in packages
library(dplyr)
# create two random dataframes
random <- data.frame(y = rnorm(30, 10), x = rnorm(30, 100), z = rnorm(30, -15))
fixed <- data.frame(y = rnorm(30, 10), x = rnorm(30, 10), z = rnorm(30, 10), a = rnorm(30, 10))
# find columns to change the values of
cols_change <- colnames(fixed)[colnames(fixed) %in% colnames(random)]
# change the value of fixed based on the corresponding column in random ####
# tidyverse
fixed %>% mutate_at(vars(cols_change), funs(. + random$.)) -> fixed2
fixed2
# base R
fixed[names(random)] <- random + fixed[names(random)]
fixed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment