如何根据多个列的值按数值间隔创建列?

How to create columns by numerical intervals from values ​of several columns?

根据整数值按数值间隔创建列。 6 个间隔(列)从 1 到 90 分成 15 个。

新列将显示该时间间隔内出现的次数。所有输入列均作为参考值。部分参考值为NA。

这些是输入列

col1 col2 col3 col4 col5 col6
11   20   22   54   73   86
1    32   64   69   NA   NA

预期输出

col1 col2 col3 col4 col5 col6  1to15 16to30 31to45 46to60 61to75 76to90
11   20   22   54   73   86      1      2      0      1      1      1
1    32   64   69   NA   NA      1      0      1      0      2      0

我看过一些使用 cut() 的示例,但我无法将其适应上述内容

这是一个使用 cut:

的解决方案
tmp <- 
t(apply(
  df, # assume df is your dataframe or matrix
  1, 
  function(x) table(cut(x, seq(1, 91, 15), right = FALSE))
))

cbind(df, tmp)
#  col1 col2 col3 col4 col5 col6 [1,16) [16,31) [31,46) [46,61) [61,76) [76,91)
#1   11   20   22   54   73   86      1       2       0       1       1       1
#2    1   32   64   69   NA   NA      1       0       1       0       2       0

如果您希望以不同方式命名列,cut 有一个 labels 参数,您可以修改。

这是另一个答案,比@DiceboyT 的答案稍长,但对某些人可能有用。

数据

df <- structure(
  list(
    col1 = c(11L, 1L),
    col2 = c(20L, 32L),
    col3 = c(22L, 64L),
    col4 = c(54L, 69L),
    col5 = c(73L, NA),
    col6 = c(86L, NA)),
  class = "data.frame",
  row.names = c(NA, -2L))

答案码

librar(tidyverse)

left_join(
  df %>% rowid_to_column("row"),
df %>%
  rowid_to_column("row") %>%
  gather(var, value, -row) %>% 
  mutate(cuts = cut(value, seq(1, 90, by = 15)),
         cuts = str_remove_all(cuts, "[\(\]]"),
         cuts = str_replace(cuts, ",", "to"),
         cuts = fct_inorder(cuts)) %>%
  count(row, cuts) %>%
  filter(!is.na(cuts)) %>%
  spread(cuts, n, fill = 0)
)