cut() 并用相同的中断和标签标记 tibble 中的所有内容

cut() and label eveything in tibble by the same breaks and labels

我得到了 that is 8984 times 155 where I need to cut() and label all all columns in the same way, i.e. using the same cut and the same labels to create a new labeled 。我该如何以简单的方式做到这一点?

这里是3次3 to simulate my 8984 times 155

# install.packages(c("tidyverse", "lubridate"), dependencies = TRUE)
require(tidyverse)
df <- tibble(x = 1:3, y = c(4, NA, 6))
df <- df %>% mutate(iD = row_number())
#> # A tibble: 3 x 3
#>       x     y    iD
#>   <int> <dbl> <int>
#> 1     1  4.00     1
#> 2     2 NA        2
#> 3     3  6.00     3

现在,我目前是这样标记的,我意识到我可以创建一个 breaks 对象和一个 labels 对象并重新使用它们,但是没有办法让我可以离开重复 mutate() 通话?

df_labeled <-  df %>% mutate(x = cut(x, breaks = c(-Inf,1,3,6),
   labels = c('Low', 'middle', 'high'), include.lowest = TRUE),
                             y = cut(y, breaks = c(-Inf,1,3,6),
   labels = c('Low', 'middle', 'high'), include.lowest = TRUE)) %>% 
                                                                 select(iD, x, y)

这给了我想要的,但我正在寻找更通用的方法。

df_labeled
#> # A tibble: 3 x 3
#>      iD x      y    
#>   <int> <fct>  <fct>
#> 1     1 Low    high 
#> 2     2 middle <NA> 
#> 3     3 middle high

p.s。当我调用我的 id 变量 id 时,我是唯一一个出错的人吗?

受到的启发,我目前正在试验这个

df %>% mutate_at(vars(-iD),cut(as.numeric(.), breaks = c(-Inf,1,3,6), 
            labels = c('Low', 'middle', 'high'), include.lowest = TRUE)) 

但我仍然遇到错误,

Error in cut(as.numeric(.), breaks = c(-Inf, 1, 3, 6), labels = c("Low",  : 
  (list) object cannot be coerced to type 'double'

我目前正在阅读手册来解决这个问题。

你难以应用jazzurro的评论是因为你不需要as.numeric(.):

df %>%
    mutate_at(vars(-iD), cut, breaks = c(-Inf, 1, 3, 6), include.lowest = TRUE,
              labels = c('Low', 'middle', 'high'))

# A tibble: 3 x 3
       x      y    iD
  <fctr> <fctr> <int>
1    Low   high     1
2 middle   <NA>     2
3 middle   high     3