2017-07-26 120 views
2

我有一个清单,不限次数:parameter<-2,1,3,4,5...... 我想重复的功能与参数:[R重复功能

MyFunction('2') 

MyFunction('1') 

MyFunction('3') etc. 

非常感谢您任何提示

+1

查看'lapply',类似于:'lapply(parameter,MyFunction)'。 –

回答

1

最喜欢的R中的事情,处理这个问题的方法不止一种。该tidyverse解决方案第一,其次是基础R.

purrr /图

我没有你想要的输出细节,但是从purrrmap功能会在你所描述的情况下工作。我们用功能plus_one()来演示。

library(tidyverse) # Loads purrr and other useful functions 

plus_one <- function(x) {x + 1} # Define our demo function 

parameter <- c(1,2,3,4,5,6,7,8,9) 

map(parameter, plus_one) 

map返回一个列表,这并不总是需要的。对于特定种类的输出,有专门的版本map。根据你想要做什么,你可以使用map_chr,map_int等。在这种情况下,我们可以使用map_dbl来获得返回值的向量。

map_dbl(parameter, plus_one) 

基础R

apply家族从基础R功能也可能满足您的需求。我更喜欢使用purrr,但有些人喜欢坚持内置功能。

lapply(parameter, plus_one) 
sapply(parameter, plus_one) 

您最终获得了相同的结果。

identical({map(parameter, plus_one)}, {lapply(parameter, plus_one)}) 
# [1] TRUE