Last active
December 9, 2020 07:41
-
-
Save rhilfi/7c924c47af78a9f5326fbde051d49eb8 to your computer and use it in GitHub Desktop.
calculate_with_mutate_at #R
This file contains 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
# calculate with mutate_at | |
# see also here: https://suzan.rbind.io/2018/02/dplyr-tutorial-2/ | |
# create an example data frame #### | |
library(tidyverse) | |
id<-1:10 | |
item1<-c(2,3,2,4,3,2,1,0,2,1) | |
item2<-c(4,3,2,1,2,3,1,0,1,2) | |
age<-c(32,33,43,25,65,32,13,56,34,99) | |
data<-data.frame(id,item1, item2, age) | |
# use mutate_at to change several variables at once | |
data_2<-data %>% | |
mutate_at(vars(contains("item")), ~(4-.)) | |
# you could also add new variables instead of replacing them #### | |
data_3<-data %>% | |
mutate_at(vars(contains("item")), funs(transformed = 4-.)) # credit: https://twitter.com/TomasMcManus1/status/981187099649912832 | |
# or you could rename the variables after mutate #### | |
data_4<-data %>% | |
mutate_at(vars(contains("item")), ~(4-.)) %>% | |
rename_at(vars(contains("item")), ~paste0(.,"_transformed")) # credit: https://suzan.rbind.io/2018/02/dplyr-tutorial-2/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment