tidyr::pivot_longer() 函数不适用于将列从逻辑转换为整数的 tibble

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

我试图在 tibble 中使用 tidyr::pivot_longer() 函数,但它不起作用。我的一些数据集列是作为逻辑列导入的,因此我必须将它们转换为整数列。当我尝试使用 pivot_longer() 时,结果是错误的。这是我的问题的一个例子:

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])")

names_pattern 不正确。它将是 "(....)([1-3])" 而不是 [1:3] 或更简单地在 . 上使用 names_sep 因为这也可以在不假设末尾位数的情况下进行拆分。或者代替 [1-3] 它可以只是 (\d)

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

-输出

# 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