Learn R Programming

comprehenr (version 0.6.7)

to_list: List comprehensions for R

Description

  • to_vec is the same as 'to_list' but return vector. See examples.

  • alter return the same type as its argument but with modified elements. It is useful for altering existing data.frames or lists. See examples.

  • exclude is an auxiliary function for dropping elements in 'alter'. There are no arguments for this function.

Usage

to_list(expr)

to_vec(expr, recursive = TRUE, use.names = FALSE)

alter(expr, data = NULL)

exclude()

Arguments

expr

expression which starts with for , while or repeat.

recursive

logical. Should unlisting be applied to list components of result? See unlist for details.

use.names

logical. Should names be preserved? See unlist for details.

data

data.frame/list/vector which we want to alter

Value

list for to_list and vector for to_vec

Examples

Run this code
# NOT RUN {
# rather useless expression - squares of even numbers
to_list(for(i in 1:10) if(i %% 2==0) i*i)

# Pythagorean triples
to_list(for (x in 1:30) for (y in x:30) for (z in y:30) if (x^2 + y^2 == z^2) c(x, y, z))

colours = c("red", "green", "yellow", "blue")
things = c("house", "car", "tree")
to_vec(for(x in colours) for(y in things) paste(x, y))

# prime numbers
noprimes = to_vec(for (i in 2:7) for (j in seq(i*2, 99, i)) j)
primes = to_vec(for (x in 2:99) if(!x %in% noprimes) x)
primes

# iteration over multiple lists
to_vec(for(`i, j` in numerate(letters)) if(i %% 2==0) paste(i, j))

set.seed(123)
rand_sequence = runif(20)
# gives only locally increasing values
to_vec(for(`i, j` in lag_list(rand_sequence)) if(j>i) j)

# 'alter' examples
data(iris)
# scale numeric variables
res = alter(for(i in iris) if(is.numeric(i)) scale(i))
str(res)

# convert factors to characters
res = alter(for(i in iris) if(is.factor(i)) as.character(i))
str(res)

# exclude factors from data.frame
res = alter(for(i in iris) if(is.factor(i)) exclude())
str(res)

# 'data' argument example
# specify which columns to map with a numeric vector of positions:
res = alter(
    for(`i, value` in numerate(mtcars)) if(i %in% c(1, 4, 5)) as.character(value),
    data = mtcars
)
str(res)

# or with a vector of names:
res = alter(
    for(`name, value` in mark(mtcars)) if(name %in% c("cyl", "am")) as.character(value),
    data = mtcars
)
str(res)
# }

Run the code above in your browser using DataLab