C.Robin
C.Robin

Reputation: 1102

Turning data manipulation into a function in R

I have downloaded an .ods file from this website (UK office for national statistics). Because of the way the sheet is structured, I import it as two separate dataframes:

library(readODS)
income_pretax <- read_ods('/Users/c.robin/Downloads/NS_Table_3_1a_1819.ods', range = "A4:U103")
income_posttax <- read_ods('/Users/c.robin/Downloads/NS_Table_3_1a_1819.ods', range = "A104:U203")

I want to do some cleaning on both dataframes: changing the name of the two of the variables and recasting one of the variables as numeric. This is what I have for this, which works on a single df:

income_pretax <- income_pretax %>% 
  rename(pp_tot_income_pretax = 'Percentile point\nTotal income before tax',
         '2008-09' = '2008-09(a)')

income_pretax['2008-09'] <- as.numeric(income_pretax$'2008-09')

I'm struggling to get the above into a function though. I think it should be something like the below, but honestly I have no idea how to tell R i'm passing multiple dataframes to the function, nor how to handle multiple variables. Can anyone advise on this?

##Attempting a function
cleanvars <- function(data, varlist){
  data <- data %>% 
    rename(pp_tot_income_pretax = {{varlist}})
  
  data['2008-09'] <- as.numeric(data$'2008-09')
}

Upvotes: 0

Views: 77

Answers (2)

akrun
akrun

Reputation: 887691

We can do this in base R

nm1 <- c('mpg', 'cyl')
nm2 <- paste0("new_", nm1)
i1 <- match(nm1, names(mtcars))
names(mtcars)[i1] <- nm2

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389175

You can pass a named vector to the function.

library(dplyr)

cleanvars <- function(data, varlist){
   data %>% rename(varlist)
}

cleanvars(mtcars %>% head, c('new_mpg' = 'mpg', 'new_cyl' = 'cyl'))

#                  new_mpg new_cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4            21.0       6  160 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag        21.0       6  160 110 3.90 2.875 17.02  0  1    4    4
#Datsun 710           22.8       4  108  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive       21.4       6  258 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout    18.7       8  360 175 3.15 3.440 17.02  0  0    3    2
#Valiant              18.1       6  225 105 2.76 3.460 20.22  1  0    3    1

Upvotes: 3

Related Questions