Home > Mobile >  How to remove 2 or more columns from each dataset at the same time in R?
How to remove 2 or more columns from each dataset at the same time in R?

Time:10-27

I have 50 dataset and I need to remove the unnecessary columns. But question, how to remove them at the same time? I can only remove single column each time and my code line is increasing. I want to keep it short and simple.

alabama <- data.frame(...)
alaska <- data.frame(...)
..
..
..
wisconsin <- data.frame(...)
wyoming <- data.frame(....)


CodePudding user response:

Keep the objects in a list and then do this in a single step

lst1 <- mget(tolower(state.name))
lst2 <- lapply(lst1, subset, select = 1:2)

CodePudding user response:

This is a common question, you can search and see many answers on this website. But one of them options is using subset function,


dataframe <- data.frame(alabama = 1:5, alaska = 2:5,,,,, wisconsin = 3:5, wyoming = 4:7 ) #choose the columns you want to keep
dataframe <- subset(dataframe, select = c(alabama, alaska,,,,, wisconsin, wyoming))

If you need any explanation, let me know!

  •  Tags:  
  • r
  • Related