0

I want to rename all columns of my dataframe (expect id and t) by adding the prefix "le_". Firstly I turn the data frame from wide to long format and after specifying the columns ( named 1 - 27) I want to rename them as le_1 - le_27. Any suggestions on how to do this? I tried with rename but I got stuck.

df_long_le <- df_wide_le %>%      
  pivot_longer(cols = starts_with("le_"), names_to = c( "t", ".value"), 
  names_pattern = "le_(.*)_(.*)") %>%
  rename(df_long_le[3:29] = "le_*[1-27]")

Thank you!

This is how the dataframe looks like enter image description here

  • To make this a reproducible example, can you share your data using `dput(df_wide_le)`? – nniloc Aug 02 '21 at 19:21
  • As this is my first question in the platform I don't know how to share the data. I have created this dataframe by extracting only few variables of interest from a bigger dataset (originally a SPSS file) – user16576132 Aug 02 '21 at 21:07
  • Can you share `names(df_wide_le)` and which of those columns you want to rename? – iago Aug 02 '21 at 21:22
  • Generally you have a much better chance of getting a useful answer if you share your data and code in a way that makes it easy for others to reproduce. A data subset is perfect, but it is very difficult to help given a screenshot of your data. If you type `dput(data_subset)` you can copy the code to recreate `data_subset` and post it here. Read this for more hints: https://stackoverflow.com/a/5963610/12400385 – nniloc Aug 02 '21 at 22:11

1 Answers1

0

To change all of the columns:

colnames(df_long_le) <- paste("le", colnames(df_long_le), sep = '_')

To change all but 1 and 2:

newcolnames <- paste("le", colnames(df_long_le)[-c(1,2)], sep = '_')
colnames(df_long_le) <- c(colnames(df_long_le)[1:2], newcolnames)
gurezende
  • 176
  • 9