Learn R Programming

expss (version 0.7.1)

keep: Keep or drop elements by name/criteria in data.frame/matrix/list/vector

Description

keep selects variables/elements from data.frame by their names or by criteria (see criteria). except drops variables/elements from data.frame by their names or by criteria. There is no non-standard evaluation in these functions by design so use quotes for names of your variables or use qc. The only exception with non-standard evaluation is %to%. See example. Character arguments will be expanded as with subst. a`1:2` will be translated to 'a1', 'a2'. %keep%/%except% are infix versions of these functions. Methods for list will apply keep/except to each element of the list separately. .keep/.except are versions which works with default_dataset.

Usage

keep(data, ...)

except(data, ...)

data %keep% variables

data %except% variables

.keep(...)

.except(...)

Arguments

data

data.frame/matrix/list/vector

...

column names/element names of type character or criteria/logical functions

variables

column names/element names of type character or criteria/logical functions

Value

object of the same type as data

Examples

Run this code
# NOT RUN {
keep(iris, "Sepal.Length", "Sepal.Width")  
keep(iris, qc(Sepal.Length, Sepal.Width)) # same result with non-standard eval 
except(iris, "Species")

keep(iris, "Species", other) # move 'Species' to the first position
keep(iris, to("Petal.Width")) # keep all columns up to 'Species'

except(iris, perl("^Petal")) # remove columns which names start with 'Petal'

except(iris, items(5)) # remove fifth column

keep(airquality, from("Ozone") & to("Wind")) # keep columns from 'Ozone' to 'Wind'

# the same examples with infix operators

iris %keep% c("Sepal.Length", "Sepal.Width") 
iris %keep% qc(Sepal.Length, Sepal.Width) # same result with non-standard eval
iris %except% "Species"

iris %keep% c("Species", other) # move 'Species' to the first position
iris %keep% to("Petal.Width")   # keep all columns except 'Species'

iris %except% perl("^Petal")    # remove columns which names start with 'Petal'

airquality %keep% (from("Ozone") & to("Wind")) # keep columns from 'Ozone' to 'Wind'
    
keep(airquality, Ozone %to% Wind) # the same result 
airquality %keep% (Ozone %to% Wind) # the same result 

# character expansion
dfs = data.frame(
     a = 10 %r% 5,
     b_1 = 11 %r% 5,
     b_2 = 12 %r% 5,
     b_3 = 12 %r% 5,
     b_4 = 14 %r% 5,
     b_5 = 15 %r% 5 
 )
 i = 1:5
 keep(dfs, "b_`i`")
 keep(dfs, b_1 %to% b_5) # the same result
# }

Run the code above in your browser using DataLab