Deleting multiple columns in different data sets in R

前端 未结 3 2000
一向
一向 2021-01-20 04:04

I\'m wondering if there is a good way to delete multiple columns over a few different data sets in R. I have a data set that looks like:

RangeNumber    Time         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 04:31

    I'm not sure if I should recommend these since these are pretty "destructive" methods.... Be sure that you have a backup of your original data before trying ;-)

    This approach assumes that the datasets are already in your workspace and you just want new versions of them.

    Both of these are pretty much the same. One option uses lapply() and the other uses for.

    • lapply

      lapply(ls(pattern = "data[0-9+]"),
             function(x) { assign(x, get(x)[2:3], envir = .GlobalEnv) })
      
    • for

      temp <- ls(pattern = "data[0-9+]")
      for (i in 1:length(temp)) {
        assign(temp[i], get(temp[i])[2:3])
      }
      

    Basically, ls(.etc.) will create a vector of datasets in your workspace matching the naming pattern you provide. Then, you write a small function to select the columns you want to keep.

    A less "destructive" approach would be to create new data.frames instead of overwriting the original ones. Something like this should do the trick:

    lapply(ls(pattern = "data[0-9+]"),
           function(x) { assign(paste(x, "T", sep="."), 
                                get(x)[2:3], envir = .GlobalEnv) })
    

提交回复
热议问题