tidyr::pivot_longer() function does not work with tibble with converted columns from logical to integer

Viewed 65

I'm trying to use tidyr::pivot_longer() function in a tibble, and it does not work. Some of my data set columns are imported as logical, so I have to convert them to integer columns. When I try to use pivot_longer(), the results are wrong. Here is an example of my problem:

test <- tibble(name = paste0("TEST",1:5),
               acl.1 = 1:5,
               acl.2 = 11:15,
               acl.3 = rep(NA,5),
               mcl.1 = 6:10,
               mcl.2 = 16:20,
               mcl.3 = rep(NA,5)
               )

test <- test %>% mutate(across(where(is.logical), as.integer)) # trying to convert from logical to integer
test[is.na(test)] <- 0 # trying to replace NA's with 0

testLong <- test %>%
            pivot_longer(cols = c(starts_with("acl."), starts_with("mcl.")),
            names_to = c(".value","label"),
            names_pattern = "(....)([1:3])")
1 Answers

The names_pattern is not correct. It would be "(....)([1-3])" and not [1:3] or more simply with names_sep on the . as this can also split without assuming the the number of digits at the end. Or instead of [1-3] it can be just (\\d)

library(dplyr)
library(tidyr)
test %>% 
  pivot_longer(cols = -name, names_to = c(".value", 'label'), names_sep = "\\.")

-output

# A tibble: 15 x 4
#   name  label   acl   mcl
#   <chr> <chr> <int> <int>
# 1 TEST1 1         1     6
# 2 TEST1 2        11    16
# 3 TEST1 3         0     0
# 4 TEST2 1         2     7
# 5 TEST2 2        12    17
# 6 TEST2 3         0     0
# 7 TEST3 1         3     8
# 8 TEST3 2        13    18
# 9 TEST3 3         0     0
#10 TEST4 1         4     9
#11 TEST4 2        14    19
#12 TEST4 3         0     0
#13 TEST5 1         5    10
#14 TEST5 2        15    20
#15 TEST5 3         0     0
Related