naming a column in a list manner with string in data.table

后端 未结 1 875
别那么骄傲
别那么骄傲 2021-01-15 08:07

I have a problem that I don\'t manage to solve properly in data.table. I have the following data:

plouf <- data.table(  ID = rep(LETTERS[1:10],each = 10)          


        
1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 08:53

    We can use setNames

    plouf[get(col) > 5, setNames(list(get(col)[1]), col) ,by = ID]
    

    or another option is setnames after getting the result

    setnames(plouf[get(col) > 5, .(get(col)[1]) ,by = ID], 'V1', col)[]
    #   ID X1
    #1:  A  8
    #2:  B  7
    #3:  C  6
    #4:  D 10
    #5:  F  9
    #6:  G  8
    #7:  H 10
    #8:  I  6
    #9:  J  8
    

    If we are using dplyr, then the option would be

    library(dplyr)
    plouf %>%
       filter_at(col, any_vars(.>5)) %>%
       group_by(ID) %>% 
       summarise_at(col, first)
    # A tibble: 9 x 2
    #  ID       X1
    #   
    #1 A         8
    #2 B         7
    #3 C         6
    #4 D        10
    #5 F         9
    #6 G         8
    #7 H        10
    #8 I         6
    #9 J         8
    

    Or with := and sym from rlang

    plouf %>% 
        filter(!! rlang::sym(col) > 5) %>%
        group_by(ID) %>% 
        summarise(!! col := first(!!rlang::sym(col)))
    

    0 讨论(0)
提交回复
热议问题