Consider the following simple dataset ds:
ds <- data.frame("x"=c(1,2,3), "y"=c(5,5,5))
I apply a function on some columns of ds like x and y and create two new variables named xnew and ynew. It works well:
ds[,c("xnew","ynew")] <- lapply(ds[,c("x","y")], function(x) x^2)
But suppose there ist some undefined column names like z! In this case I get the error "undefined columns selected" and nither xnew nor ynew were created.
Is there any way to skip this error and create xnew and ynew and get only an error for znew? (something like trycatch by for-loops)
ds[,c("xnew","ynew","znew")] <- lapply(ds[,c("x","y","z")], function(x) x^2)
Error in `[.data.frame`(ds, , c("x", "y", "z")) :
undefined columns selected
lapply(ds[,colnames(ds) %in% c("x","y","z")], function(x) x^2)- GKidslike:tt <- lapply(ds[,colnames(ds) %in% c("x","y","z")], function(x) x^2); ds[,paste0(names(tt), "_new")] <- tt- GKi