Last active
September 4, 2017 13:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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