timothy.s.lau
timothy.s.lau

Reputation: 1101

How to make a function to remove vectors

I'm exercising my function writing skills today. Can someone explain why the function I wrote doesn't remove columns 2 and 3 from the data frame?

data <- data.frame(x = 2, y = 3, z = 4)
rmvar <- function(x){
  lapply(X = x, FUN = function(x){
    x <- NULL})}
rmvar(data[,2:3])

Upvotes: 0

Views: 37

Answers (1)

akrun
akrun

Reputation: 887108

You could modify it

rmvar <- function(x, indx){
  x[indx] <- lapply(x[indx], FUN=function(x) x <- NULL)
  x
 }

rmvar(data, 2:3)
#  x
#1 2

As @nico mentioned in the comments, this is easier by just data[-(2:3)]. But, I guess you want to do this with lapply/NULL.

Upvotes: 1

Related Questions