Можно использовать cut
(или использовать findInterval
) для создания группы переменных, а затем преобразовать ее в широкий формат
library(dplyr)
library(tidyr)
library(stringr)
out <- df %>%
# // create grouping variable with cut based on the Height
mutate(ind = cut(Height, breaks = c(-Inf, c(0, seq(400, 2000,
by = 50 ))), labels = c('h_0_400',
str_c('h_', seq(400, 2000, by = 50)))), height_index = ind, n = 1) %>%
# // reshape to wide format
pivot_wider(names_from = ind, values_from = n, values_fill= list(n = 0))
# // missing columns are created with setdiff and assigned to 0
out[setdiff(levels(out$height_index), out$height_index)] <- 0
данные
df <- structure(list(Name = c("Plant1", "Plant2", "Plant1", "Plant3",
"Plant4"), Year = c(2010L, 2011L, 2011L, 2013L, 2016L), Height = c(340L,
60L, 1980L, 650L, 210L)), class = "data.frame", row.names = c(NA,
-5L))