Yun Tae Hwang
Yun Tae Hwang

Reputation: 1471

How to delete columns one by one in specific order in R

So, I have a dataset and need to do some works using a for loop.

Here is my fake data:

#fake data
L <- data.frame(matrix(rnorm(20), nrow=10, ncol=10))
names(L) <- c("P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", "P9","P10")

Now, I want to apply a function to the entire column and remove the column "P1". Then, run the function again and remove "P5" so on.

Here is the order of removing.

# order of removing column
R < c(P1, P5, P2, P8, P9, P4, P3, P6, P7) 

What can I try next?

Upvotes: 1

Views: 498

Answers (3)

anant
anant

Reputation: 478

Using dplyr::select and purrr:map, you could probably do something like this if you modified R to include the final column:

# example data
L <- data.frame(matrix(rnorm(20), nrow=10, ncol=10))
names(L) <- c("P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", "P9","P10")
R <- c("P1", "P5", "P2", "P8", "P9", "P4", "P3", "P6", "P7", "P10")

res_list <- 1:ncol(L) %>%
  map(~select(L[R], .x:ncol(L)))

L[R] is used to permute the columns into the order you want them removed. The result is a list of dataframes you can iterate over.

Upvotes: 0

Brian Davis
Brian Davis

Reputation: 992

Since your column names are ordered consecutively, you can do this:

i <- c(1,5,2,8,9,4,3,6,7)
lapply(i,function(x) L[,-x])

Upvotes: 0

Julien Navarre
Julien Navarre

Reputation: 7830

It depends on the output you desire but I would use lapply so each data frame subset is saved as list element :

R <- c("P1", "P5", "P2", "P8", "P9", "P4", "P3", "P6", "P7") lapply(seq_along(R), function(i) L[-which(names(L) %in% R[1L:i])])

Upvotes: 2

Related Questions