library(tidyverse) # ------------------------------------------------------------------------- # here I create a long table where I filter out negative occurences spe_long <- tibble( ID = rep(1:100, each = 20), TAXON = paste0('spe', rep(1:100, 20)), `P/A` = sample(c(0,1), 2000, prob= c(7,3), replace = T) ) %>% filter(`P/A` != 0) spe_long # here it is # ------------------------------------------------------------------------- # now I want to convert this long table into wide formate # the function needs two parameters, i.e. where to take variables names_from and where to take ~cover~ values_from spe_long %>% pivot_wider(names_from = TAXON, values_from =`P/A`) # be aware that everything else is just omitted from spreading into columns, which in our case applies for IDs # this output produces NAs; to get no nas, we have to add one more argument wide <- spe_long %>% pivot_wider(names_from = TAXON, values_from =`P/A`, values_fill = 0) # I add just 0 here, because my columns are of type 'double', if they were character, I would have to put there '0' or "0" wide # here we have the output # the IDs are however still present here # we can remove them using select function wide %>% dplyr::select(-ID) # ------------------------------------------------------------------------- # and if you want to get back to the long form, here is the function # wide still has IDs here, becase we didnt store the line 28 into a file wide %>% pivot_longer(-'ID') # this says: "put all values into one column and names into other column, but skip 'ID' # alternatively spe_long_again <- wide %>% pivot_longer(-1) # ------------------------------------------------------------------------- # however! the table is now almost 10000 rows long, which is way more than spe_long that we used on the beginning spe_long_again spe_long # it is because we have the 0 there, we can filter them out like this: spe_long_again %>% filter(value != 0)