Home > Enterprise >  How to rename and add "_cntr" to the middle of the columns of a dataframe within a functio
How to rename and add "_cntr" to the middle of the columns of a dataframe within a functio

Time:11-18

I am new to programming in R and I have had to make a function that collects a dataframe and returns that same dataframe with twice as many columns as the original and in those new columns, the values have to be the original value minus the mean (the mean is row 51 of the dataframe). The fact is that I have made the function and it works, the only thing I need to do is rename column 9:16 of the dataframe, they have to have the same name as the original columns and add "_cntr" to them.

I had thought to add the _cntr with the paste function, but it does not work for me or I am not using it well, I had thought something like this:

nom = paste("cntr",sep = '_')
colnames(state.df3) = nom

and this put it inside the function that I will share next, but this changes the name of the first column by centr and leaves the rest of the columns with the value NA.

If I do that:

nom = paste("cntr",9:16,sep = '_')
colnames(state.df3) = nom

It returns cntr1, cntr2, cntr3 ... and I don't want it to return that, I want it to return "Population_cntr", "Income_cntr", "Illiteracy_cntr" ... all that from column 9 to 16 (since is where duplicates start)

The dataframe that I am using as a test can be accessed here:

state.df = as.data.frame(state.x77)

And this is the function that I have done so far, I would only need to modify the names of the 9:16 columns.

mi_funcion <- function(df) { 
  row_medias <- tail(df, 1)
  row_resto <- head(df, -1)
  tmp <- rbind(row_resto - as.list(row_medias), row_medias)
  resultado = cbind(df, tmp)
  return(resultado)
}

If someone could give me a hand and tell me where I am failing I would be very grateful.

CodePudding user response:

This is just an example so for yours replace 1:2 with 9:16

df <- data.frame(Population = c(10),Income = c(20000),Illiteracy = ("Y"))
df

 Population Income Illiteracy
1         10  20000          Y

colnames(df)[1:2] <- paste(colnames(df)[1:2],"cntr", sep = "_")

Output:

df

 Population_cntr Income_cntr Illiteracy
1              10       20000          Y

CodePudding user response:

We can also use dplyr's rename_with:

library(dplyr)

state.df3 %>% rename_with(~paste(.x, "cntr",sep = '_'), .cols = everything())
  • Related