使用lapply将字符向量的名称和值传递给函数

时间:2015-01-25 16:33:24

标签: r

我有一个带两个参数的函数:

my.function <- function(name, value) {

  print(name)

  print(value) #using print as example

}

我有一个具有名称和值的整数向量:

  freq.chars <- table(sample(LETTERS[1:5], 10, replace=TRUE))

我想使用lapply将my.function应用于freq.chars,其中每个项的名称作为x传递,并且值(在本例中为frequency)以y传递。

当我尝试时,

lapply(names(freq.chars), my.function) 

我收到错误&#34; value&#34;缺少没有默认值。

我也试过

 lapply(names(freq.chars), my.function, name = names(freq.chars), value = freq.chars)

,在这种情况下我得到一个错误:未使用的参数值= c(...)。

对于编辑和清晰度感到抱歉,我是新来的......

2 个答案:

答案 0 :(得分:3)

我们使用此测试数据:

set.seed(123) # needed for reproducibility
char.vector <- sample(LETTERS[1:5], 10, replace=TRUE)
freq.chars <- table(char.vector)

以下是几种变体:

# 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]]))

请注意mapplysapply有一个可选的USE.NAMES参数,用于控制是否推断出结果的名称以及可选的simplify参数('SIMPLIFY {{1} } mapply`)控制是否简化列表输出。使用这些参数进一步控制。

更新完全修改后的演示文稿。

答案 1 :(得分:0)

如果您只想在函数中添加另一个参数,请在函数名称(lapply中的第3个parm)之后指定它。

lapply(names(freq.chars), my.function, char.vector)