“longer object length is not a multiple of shorter object length”

后端 未结 3 1089
梦谈多话
梦谈多话 2021-01-21 16:05

I have this dataset -

print(df)

  object    group   
1 apple      A    
1 banana     B    
1 pear       A    
1 robot      C

print(df2)

  object    group   
         


        
3条回答
  •  -上瘾入骨i
    2021-01-21 16:42

    If you need a tidyverse option, we can use map_dbl

    purrr::map_dbl(df$object, ~ length(df2[df2$object == .,]$object))
    #[1] 3 1 0 3
    

    which can be also calculated with sum

    purrr::map_dbl(df$object, ~ sum(df2$object == .))
    

    So in mutate we can add

    df %>%
      mutate(reference = map_dbl(object,  ~ sum(df2$object == .)))
    
    #  object group reference
    #1  apple     A         3
    #2 banana     B         1
    #3   pear     A         0
    #4  robot     C         3
    

    The similar base R option is sapply

    sapply(df$object, function(x) sum(df2$object == x))
    
    # apple banana   pear  robot 
    #     3      1      0      3 
    

提交回复
热议问题