R dplyr join by range or virtual column

后端 未结 6 1329
独厮守ぢ
独厮守ぢ 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:09

    We can use sapply for this

    library(tibble)
    
    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 <- cbind(d, data.frame(class = (unlist(sapply(d$value, function (x) r[which(x >= r$from & x < r$to), "class"]))) ) )
    
    d
       value class
    1    1.0     A
    2    1.2     A
    3    1.4     A
    4    1.6     A
    5    1.8     A
    6    2.0     B
    7    2.2     B
    8    2.4     B
    9    2.6     B
    10   2.8     B
    11   3.0     C
    12   3.2     C
    13   3.4     C
    14   3.6     C
    15   3.8     C
    16   4.0     D
    17   4.2     D
    18   4.4     D
    19   4.6     D
    20   4.8     D
    21   5.0     E
    22   5.2     E
    23   5.4     E
    24   5.6     E
    25   5.8     E
    26   6.0     F 
    

提交回复
热议问题