Reputation: 635
I have a function that takes two arguments:
my.function <- function(name, value) {
print(name)
print(value) #using print as example
}
I have an integer vector that has names and values:
freq.chars <- table(sample(LETTERS[1:5], 10, replace=TRUE))
I'd like to use lapply to apply my.function to freq.chars where the name of each item is passed in as x, and the value (in this case frequency) is passed in as y.
When I try,
lapply(names(freq.chars), my.function)
I get an error that "value" is missing with no default.
I've also tried
lapply(names(freq.chars), my.function, name = names(freq.chars), value = freq.chars)
, in which case I get an error: unused argument value = c(...).
Sorry for the edits and clarity, I'm new at this...
Upvotes: 1
Views: 1637
Reputation: 269481
We use this test data:
set.seed(123) # needed for reproducibility
char.vector <- sample(LETTERS[1:5], 10, replace=TRUE)
freq.chars <- table(char.vector)
Here are several variations:
# 1. iterate simultaneously over names and values
mapply(my.function, names(freq.chars), unname(freq.chars))
# 2. same code except Map replaces mapply. Map returns a list.
Map(my.function, names(freq.chars), unname(freq.chars))
# 3. iterate over index and then turn index into names and values
sapply(seq_along(freq.chars),
function(i) my.function(names(freq.chars)[i], unname(freq.chars)[i]))
# 4. same code as last one except lapply replaces sapply. Returns list.
lapply(seq_along(freq.chars),
function(i) my.function(names(freq.chars)[i], unname(freq.chars)[i]))
# 5. this iterates over names rather than over an index
sapply(names(freq.chars), function(nm) my.function(nm, freq.chars[[nm]]))
# 6. same code as last one except lapply replaces sapply. Returns list.
lapply(names(freq.chars), function(nm) my.function(nm, freq.chars[[nm]]))
Note that mapply
and sapply
have an optional USE.NAMES
argument that controls whether names are inferred for the result and an optional simplify
argument ('SIMPLIFYfor
mapply`) which controls whether list output is simplified. Use these arguments for further control.
Update Completely revised presentation.
Upvotes: 4
Reputation: 20016
If you just want to add another parameter to your function, specify it after the function name (3rd parm in lapply).
lapply(names(freq.chars), my.function, char.vector)
Upvotes: 0