library(tidyverse)
Using the sample data below, I have two dataframes - Df1 and Df2. I'm attempting to create a simple function that selects columns by string - in this case columns in both dataframes that start with "Person" as well as all columns that contain "Phone".
Next, I would like to rename the "Person" column in both dataframes to "Id".
However, I'm having trouble getting the rename function to work correctly.
Here is a first attempt...
Funs<-function(Df){
Df%>%select(starts_with("Person"),contains("Phone"))%>%
rename_at(vars(starts_with("Person"),"Id"))
}
Below are some other variations of "rename" that I tried, but didn't work...
rename_at(vars(starts_with("Person"),funs("Id"=.)))
rename("Id"=names(.)[1])
How should I correct this? I tried to find similar questions on this site since it seems simple enough, but I couldn't find anything that works...
Sample Data:
`Person #`<-c(199,148,148,145,177,165,144,121,188,188,188,111)
`Phone #1`<-c(6532881717,6572231223,6541132112,6457886543,6548887777,7372222222,6451123425,6783450101,7890986543,6785554444,8764443344,6453348736)
`Phone #2`<-c(NA,NA,NA,NA,NA,7372222222,NA,NA,NA,6785554444,NA,NA)
Animals<-c("Cat","Dog","Elephant","Giraffe","Bird","Snake","Skunk","Raccoon","Moose","Turtle","Beaver","Porcupine")
Df1<-data.frame(`Person #`,`Phone #1`,`Phone #2`, Animals)
`Person ID #`<-c(199,148,142,145,177,165,144,121,182,109,188,111)
`Phone s 1`<-c(6532881717,6572231223,6541132112,6457886543,6548887777,7372222222,6451123425,6783450101,7890986543,6785554400,8764443344,6453348736)
`Phone s 2`<-c(NA,NA,NA,NA,NA,7372222222,NA,NA,NA,6785554444,NA,NA)
Animals<-c("Cat","Dog","Elephant","Giraffe","Bird","Snake","Skunk","Raccoon","Moose","Turtle","Beaver","Porcupine")
Df2<-data.frame(`Person ID #`,`Phone s 1`,`Phone s 2`, Animals)