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)
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
# <chr> <int>
#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)))