1

I want to be able to apply a function over a subset of columns, and return those columns that have been manipulated along with the rest of the data columns that weren't touched. Is there a way to do this with data.table. I wasn't able to figure out the syntax.

In this example I have NAs and want to overwrite them with something else for a few different columns. I need a way to also return other columns that weren't touched.

library(data.table)

# make data set
a <- sample(c(letters[1:5], NA), 50, replace=TRUE)
b <- sample(c(LETTERS[1:5], NA), 50, replace=TRUE)
c <- sample(runif(50))

x <- data.table(a,b,c)

# function to apply to a single column
overwriteNA <- function(vec, new="") ifelse(is.na(vec), new, vec)

# Only returns .SDcols but would like to also include rest of columns in data.table
x[, lapply(.SD, overwriteNA), .SDcols=c("a", "b")]

# Need something along these lines
x[, `:=` lapply(.SD, overwriteNA), .SDcols=c("a", "b")]
iAmAMutt
  • 13
  • 3

1 Answers1

9

Try

x[,  c("a", "b") := lapply(.SD, overwriteNA), .SDcols = c("a", "b")]

Edit:

Per OPs additional request.

myCols <- c("a", "b")  
x[, (myCols) := lapply(.SD, overwriteNA), .SDcols = myCols]
David Arenburg
  • 91,361
  • 17
  • 137
  • 196