Home > Net >  Subsetting within a function using data.table and is.na(x) in R
Subsetting within a function using data.table and is.na(x) in R

Time:04-23

I am trying to subset a data.table within a function, but subsetting by using !is.na(x) is not working. I know it could work, because as I was building my example on a still simpler problem, the subset call worked fine.

library(data.table)
library(ggpubr)

tj = as.data.table(cbind(Name = c("Tom", "Tom", "Tim", "Jerry", NA, "Jerry", "Tim", NA), 
                         var1 = c(12, 12, 20, 30, 31, 21, 21, 31), 
                         var2 = c(12, 11, 27, 32, 31, 11, 21, 41),
                         var3 = c(10, 10,11, 13, 12, 12, 11, 10), 
                         time = as.numeric(c(1, 2, 1,1, 1,2,2,2))))

plot.tj<- function(dat = tj, color = NULL) {
  
  name <- names(dat)[2:4] # a factor of names to loop over
  
  for (i in seq_along(name)) {
    plotms <- ggline(dat[!is.na(color),], x = "time", y = name[i], color = color)
    print(plotms)
  
    }
}

plot.tj(color = "Name")

The expected output are the 3 var graphs, but without the NA group.

CodePudding user response:

The thing is that your variable color is a character, so you must call it with get to subset in your data.table. This works:

plot.tj<- function(dat = tj, color = NULL) {
  
  name <- names(dat)[2:4] # a factor of names to loop over
  
  for (i in seq_along(name)) {
    plotms <- ggline(dat[!is.na(get(color)),], x = "time", y = name[i], color = color)
    print(plotms)
    
  }
}

plot.tj(color = "Name")
  • Related