1

I have a data table:

(f <- data.table(id1=c(1,2,3,1,2,3),
                 v=c(1,NA,NA,2,3,4),
                 key="id1"))
  id1  v
1:   1  1
2:   1  2
3:   2 NA
4:   2  3
5:   3 NA
6:   3  4

when I try to set missing v from the present value in the group:

> f[,v[is.na(v)] := v[which(!is.na(v))[1]], by="id1"]
Error in eval(expr, envir, enclos) : object 'v' not found
Calls: [ -> [.data.table -> eval -> eval

Obviously, I am missing something very simple...

sds
  • 58,617
  • 29
  • 161
  • 278
  • 2
    that feature doesn't exist yet - https://r-forge.r-project.org/tracker/index.php?func=detail&aid=2793&group_id=240&atid=978 – eddi Mar 17 '14 at 19:19
  • With that example, I guess you can use it in `i` instead of on the LHS of `:=`, though, since your condition does not depend on the id1 group you're in: `f[v%%2==0,v:=10L*v[1],by=id1]` – Frank Mar 17 '14 at 19:22
  • @Frank: please see edit, this is not quite what I need – sds Mar 17 '14 at 19:30

1 Answers1

3

This is one solution:

f[, v:={
  ok <- !is.na(v)
  ifelse(ok,v,v[ok][1])
}, by=id1]

Note that if v is entirely NA for one group, it will stay that way:

f  <- data.table(id1=c(1,2,3,1,2,3),v=c(1,NA,NA,2,3,4),key="id1")
ff <- rbind(f,list(4L,NA),list(4L,NA))
ff[,v:={ok <- !is.na(v);ifelse(ok,v,v[ok][1])},by=id1]
Frank
  • 66,179
  • 8
  • 96
  • 180