Capper
Capper

Reputation: 59

How can I drop columns in a loop in RStudio?

I have tables A, B, and C, and they all have columns X, Y, and Z,

I would like to drop columns in a loop from different tables.

My code is as follows

for (i in c(A, B, C)) {
  for (j in c(X, Y, Z)) {
    (i$j <- NULL)
  }
}

My error message tells objects X,Y,Z weren't found. I believe my problem is in lack of use of apostrophes in tables and column names, but doing so yields the error message "Coercing LHS to a list"

Upvotes: 1

Views: 74

Answers (2)

akrun
akrun

Reputation: 887128

We can place the datasets in a list, loop over the list with lapply, select the columns, assign (<-) to NULL and return the data. Here, function(x) is the lambda function

lst1 <- lapply(list(A, B, C), function(x) {x[c('X', 'Y', 'Z')] <- NULL; x})

The return output is a list of datasets. If we want to update the original objects, use list2env:

names(lst1) <- c("A", "B", "C")
list2env(lst1, .GlobalEnv)

Using a for loop, we can avoid the nested loop as the assignment to NULL is vectorized. We loop over the object names as a string and get the value of the object. Assign the columns to NULL and update the original object:

for(nm in c("A", "B", "C")) {
    # // Get the value of dataset
    tmp <- get(nm)
    # // Assign columns to NULL
    tmp[c("X", "Y", "Z")] <- NULL
    # // Update the original object
    assign(nm, tmp)
 }

Upvotes: 3

ThomasIsCoding
ThomasIsCoding

Reputation: 101393

Here is another option but not recommended (better by using the @akrun's answer)

eval(
  str2expression(
    paste0(
      sprintf("%s['%s']<-NULL", c("A", "B", "C"), c("X", "Y", "Z")),
      collapse = ";"
    )
  )
)

Upvotes: 1

Related Questions