Learn R Programming

expss (version 0.5.5)

vars_range: Get range of variables/variables by pattern/by name

Description

  • %to% returns all variables with names in range from pattern_num1 to pattern_num2 (similar to SPSS 'to'). Result doesn't depend from order of variables in data.frame. 'num1' and 'num2' should be numbers. Results are always arranged in ascending order and include all variables with such pattern even if these variables located in different parts of dataframe. vars_range has the same functionality but intended for programming.
  • vars_pattern returns all variables by pattern (regular expression). Functions with word 'list' in name return lists of variables instead of dataframes.
  • vars returns all variables by their names. Expressions in backticks inside characters will be expanded as with subst.

Functions with word 'list' in name return lists of variables instead of dataframes.

Usage

vars_range(start, end)
vars_range_list(start, end)
e1 %to% e2
e1 %to_list% e2
vars_pattern_list(pattern)
vars_pattern(pattern)
vars_list(...)
vars(...)

Arguments

start
character Name of start variable (e. g. a_1)
end
character Name of start variable (e. g. a_5)
e1
unquoted name of start variable (e. g. a_1)
e2
unquoted name of start variable (e. g. a_5)
pattern
character pattern of variable(-s) name
...
characters names of variables.

Value

data.frame/list with variables

Examples

Run this code

# In global environement
aa = rep(10, 5)
b = rep(20, 5)
a1 = rep(1, 5)
a2 = rep(2, 5)
a3 = rep(3, 5)
a4 = rep(4, 5)
a5 = rep(5, 5)

# identical results
vars_range("a1", "a5")
a1 %to% a5
vars("a`1:5`")
vars_pattern("^a[0-9]$")

# sum each row
sum_row(a1 %to% a5)

# In data.frame
dfs = data.frame(
    aa = rep(10, 5),
    b_ = rep(20, 5),
    b_1 = rep(11, 5),
    b_2 = rep(12, 5),
    b_3 = rep(13, 5),
    b_4 = rep(14, 5),
    b_5 = rep(15, 5) 
)

# all variables that starts with 'b'
with(dfs, vars_pattern("^b"))

# calculate sum of b_* variables
modify(dfs,{
    b_total = sum_row(b_1 %to% b_5)
    b_total2 = sum_row(vars("b_`1:5`"))
})


Run the code above in your browser using DataLab