How to efficiently change range of columns from character to numeric

Hi all,

I have a large faunal abundance data set that I want to eventually use the vegan package to play with. However, I am struggling to change my sample site variables (columns 2:108) to numeric whilst keeping my Taxa ID variable a character column. Anything I've tried so far changes the enter data frame or I'm missing the key bits to tell R.

Is there a way to change a range of variables (2:108) to numeric using dplyr or purrr?

Script I've tried:

AbundanceSamTest <- mutate_at(AbundanceSam, as.numeric(c(2:108)))

#selecting the columns I want to change but creating a new df that just removes my Taxa ID
AbundanceSamTest <- AbundanceSam %>% select(c(2:108))

My df:

# A tibble: 443 × 108
   `Taxa ID`   S001_F1 S001_F2 S001_F3 S002_F1 S002_F2 S002_F3 S003_F1 S003_F2 S003_F3 S004_F1 S004_F2 S004_F3
   <chr>       <chr>   <chr>   <chr>   <chr>   <chr>   <chr>   <chr>   <chr>   <chr>   <chr>   <chr>   <chr>  
 1 Chromista   -       -       -       -       -       -       -       -       -       -       -       -      
 2 Ciliophora  -       -       -       P       -       -       -       -       -       -       -       -      
 3 Folliculin… -       -       -       -       -       -       -       -       -       -       -       -      
 4 Animalia    -       -       -       -       -       -       -       -       -       -       -       -      
 5 Porifera    -       -       -       -       -       -       -       -       -       -       -       -      
 6 Leucosolen… -       -       -       -       -       -       -       -       -       -       -       -      
 7 Sycon       -       -       -       -       -       -       -       -       -       -       -       -      
 8 Tubulariid… -       -       -       -       -       -       -       -       -       -       -       -      
 9 Eudendrium  -       -       -       -       -       -       -       -       -       -       -       -      
10 Bougainvil… -       -       -       -       -       -       -       -       -       -       -       -

Thanks for any help! :smiley:

So here's an idea with a very short sample table :


tibble::tibble(`Taxa ID` = as.character(letters), as.character(1), as.character(2)) %>%
  mutate(across(2:last_col(), ~ as.numeric(.)))

select only chooses columns but doesn't do any transformation.
across() inside mutate allows you to perform the operation on multiple columns
mutate_at is superseded and slow so use across :slight_smile:

If you wanted to use mutate_at, here's how :

tibble::tibble(`Taxa ID` = as.character(letters), as.character(1), as.character(2)) %>% 
mutate_at(2:3, ~ as.numeric(.))

Ah amazing, that did the trick! Thank you very much for the help! :smiley:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.