R dplyr join by range or virtual column

后端 未结 6 1332
独厮守ぢ
独厮守ぢ 2020-12-10 16:33

I want to join two tibbles by a range or a virtual column. but it seems the by - parameter just allow to handle chr oder vector(chr) o

6条回答
  •  既然无缘
    2020-12-10 17:16

    You use the cut function to create a "class" in object d and then use a left join.

    d <- tibble(value = seq(1,6, by = 0.2))
    r <- tibble(from = seq(1,6), to = c(seq(2,6),Inf), class = LETTERS[seq(1,6)])
    
    d[["class"]] <- cut(d[["value"]], c(0,2,3,4,5,6,Inf), c('A',"B", "C", "D", "E", "F"), right = FALSE)
    d <- left_join(d, r)
    

    To get the right buckets, you just need to work with the cut function to get what you want.

提交回复
热议问题