DPLYR: Convert multiple columns from character to integer

Viewed 3398

I am working with a long table, but need to convert (part of) it to a wide table to use the data in the staistical package Vegan. However, when I use the pivot-wider function, all columns end up as characters. I can't find the solution how to convert the colums (with scientific species names as headers) into integers. I've read many posts but all solutions so far won't work. The code I used to create the table:

biota_C <- (biota_species) %>%
  ungroup() %>% 
  select(Species, Station, Numbers) %>%
  pivot_wider(names_from = Station, values_from = Numbers) %>%
  t() %>%
  row_to_names(row_number = 1)

The resulting table looks fine to me except for the datatypes.Species table

> glimpse(biota_C)
 chr [1:306, 1:27] "0" "1" "0" " 0" " 1" " 2" "1" "2" "0" "4" "0" "0" "0" "0" "0" "3" "0" "1" "0" "0" "0" " 0" ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:306] "X00A2" "X00A4" "X00A6" "X00B2" ...
  ..$ : chr [1:27] "Aphelochaeta marioni" "Arenicola marine" "Aricidea minuta" "Bathyporeia saris" ...

Obviously I am overlooking something.

Best, Berry

3 Answers

You transposed the whole data.frame with the row.names, hence everything is converted to character.

try something like this:

df = data.frame(Species = rep(c("Aphelochaeta marioni","Arenicola marine","Aricidea minuta","Bathyporeia saris"),each=5),
Station=rep(letters[1:5],4),Numbers=rpois(20,20))

df %>% 
pivot_wider(names_from = Station, values_from = Numbers) %>%
column_to_rownames("Species") %>% 
t() %>% glimpse()

 int [1:5, 1:4] 15 19 19 22 27 25 20 21 17 23 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:5] "a" "b" "c" "d" ...
  ..$ : chr [1:4] "Aphelochaeta marioni" "Arenicola marine" "Aricidea minuta" "Bathyporeia saris"

Looking at the picture of the table, you can see some additional whitespace in the species table, so the columns in this table are characters. You can use mutate_all from dplyr together with as.numeric to convert the type:

biota_C <- biota_C %>% 
  mutate_all(as.numeric)

We can use across with mutate in dplyr 1.0.0

library(dplyr)
biota_C <- biota_C  %>%
              mutate(across(everything(), as.numeric))
Related