You can try using the devel version of data.table i.e. v1.9.5 . Installation instructions for the devel version: here
library(data.table)#v1.9.5+ setDT(df1)[, daily_v_ID:= ifelse((1:.N)==1L, uniqueN(v), NA) , by = .(ID, Date)]
or
setDT(df1)[, daily_v_ID := c(uniqueN(v), rep(NA, .N-1)), by = .(ID, Date)]
Or as suggested by @David Arenburg
indx <- setDT(df1)[, .(.I[1L], uniqueN(v)), by = .(ID, Date)] df1[indx$V1, daily_v_ID := indx$V2]
Or using dplyr
library(dplyr) df1 %>% group_by(ID,Date) %>% mutate(daily_v_ID= ifelse(row_number()==1, n_distinct(v), NA))
Or using base R
df1$daily_v_ID <- with(df1, ave(as.numeric(factor(v)), Date,ID, FUN= function(x) NA^(seq_along(x)!=1)*length(unique(x))))
Update
For the edited message, we create a variable ('daily_v_ID'), getting length(v) or in data.table , we can use .N
setDT(df1)[, c('daily_v_distinguish_ID', 'daily_v_ID'):= list( c(uniqueN(v), rep(NA, .N-1)), .N), by = .(ID, Date)] df1
NOTE: uniqueN is introduced in v1.9.5 . For earlier versions, we can use unique(length(v))
Or using dplyr
df1 %>% group_by(ID, Date) %>% mutate(daily_v_distinguish_ID = ifelse(row_number()==1, n_distinct(v), NA), daily_v_ID =n())