【问题标题】:tidyr::pivot_longer() function does not work with tibble with converted columns from logical to integertidyr::pivot_longer() 函数不适用于将列从逻辑转换为整数的 tibble
【发布时间】:2021-07-26 07:58:53
【问题描述】:

我正在尝试在 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])")

【问题讨论】:

    标签: r dplyr tidyverse tidyr


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2016-05-09
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多