How to edit all column names to replace a certain character in R?

Viewed 333

I'm working with a large dataset of SNPs and some of them are formatted in a way that makes them difficult to work with a machine learning package I'm using. Specifically, the hyphen in some of the column names is causing problems so I'm trying to go through and replace them with an underscore. I know there are probably multiple ways of doing this but this is the one I was trying with my limited knowledge of R, using lapply and str_replace:

library(tidyverse)
    
    exampleData = tribble(
      ~SNP-1_1, ~SNP-1_2, ~SNP-2_2, ~SNP-2_3,
      0, 1, 1, 0,
      1, 0, 1, 0, 
      0, 0, 0, 1
    )
    
    colnames = names(exampleData)
    colnames = lapply(colnames, str_replace("-", "_"))

This, however, causes the error: Error in fix_replacement(replacement) : argument "replacement" is missing, with no default. My understanding of lapply is that it should take colnames and apply each of the elements individually to str_replace, which should in turn mean that all 3 necessary arguments of str_replace should be there. Does someone know what's going on here? Or if you have a better way of editing the column names I'd be happy to listen to that too.

2 Answers

str_replace is vectorized. So, there is no need to loop over the column names. Also, the output of lapply is a list and not a vector along with the fact that there is no lambda call in lapply (If we are passing named arguments, there is no need for ()

library(stringr)
names(exampleData) <- str_replace(names(exampleData), "-", "_")

Or use clean_names from janitor

library(janitor)
exampleData <- exampleData %>%
            clean_names()

Base R using gsub:

colnames(exampleData) = gsub("-", "_", colnames(exampleData))
  SNP_1_1 SNP_1_2 SNP_2_2 SNP_2_3
    <dbl>   <dbl>   <dbl>   <dbl>
1       0       1       1       0
2       1       0       1       0
3       0       0       0       1
Related