mapply函数的第二个参数作为R中的向量

mapply函数的第二个参数作为R中的向量,r,list,vector,mapply,R,List,Vector,Mapply,我知道标题有点混乱,所以很抱歉。 首先是生成我们需要的数据的一些代码: ref_variables=LETTERS[1:10] # Function to generate one dataset generate_df=function(){ row=100 d0=seq(1:100) for (i in seq_along(ref_variables)){ dtemp=sample(seq(1:row),row,TRUE) d0=data.frame(d0,dtemp) } d0[,

我知道标题有点混乱,所以很抱歉。 首先是生成我们需要的数据的一些代码:

ref_variables=LETTERS[1:10]
# Function to generate one dataset
generate_df=function(){
row=100
d0=seq(1:100)
for (i in seq_along(ref_variables)){
  dtemp=sample(seq(1:row),row,TRUE)
  d0=data.frame(d0,dtemp)
}
d0[,1]=NULL
names(d0)=ref_variables
return(d0)
}

# Generating a list of dataset
list_of_df=lapply(seq(1:100),function (x){
  generate_df()
} )

# Générating a list of vectors
df_vector=sample(ref_variables,3,FALSE)
for (i in seq(2,100)){
tmp=sample(ref_variables,3,FALSE)
df_vector=rbind(df_vector,tmp)
}
list_of_vector <- split(df_vector, seq(nrow(df_vector)))
我得到了一个data.frame列表和一个向量列表。所以我想把data.frame映射到向量,根据它们作为某个函数的参数的位置。我特别想参加:

some_function(list_of_df[[1]],unlist(list_of_vector[[1]]))
some_function(list_of_df[[2]],unlist(list_of_vector[[2]]))
some_function(list_of_df[[3]],unlist(list_of_vector[[3]]))
and so on ...
因此,我决定将mapply函数用于:

big_results=mapply(some_function,
                   list_of_df,
                   list_of_vector)

但是,big_结果的长度是300,尽管我只期望100。显然,结果也不是我所期望的。有人知道这里发生了什么以及如何修复吗?

我们需要使用
Map

r1 <- Map(function(x,y) x[,y], list_of_df, list_of_vector)
length(r1)
#[1] 100

Map
只是带有
SIMPLIFY=FALSE
选项的
mapply
的包装器。当对象维度相同时,会简化为
mapply
的矩阵,因为默认选项为
SIMPLIFY=TRUE

r3 <- mapply(function(x,y) x[,y], list_of_df, list_of_vector)
length(r3)
#[1] 300

哇,太棒了!对不起,我知道我可以在谷歌上搜索,但既然你可能会胜任,你能告诉我什么是包装器吗?“我从来没能理解它。@汉斯格利克只要在你的控制台上键入
Map
,它就会给出
函数(f,…{f
r2 <- mapply(function(x,y) x[,y], list_of_df, list_of_vector, SIMPLIFY=FALSE)
length(r2)
#[1] 100
r3 <- mapply(function(x,y) x[,y], list_of_df, list_of_vector)
length(r3)
#[1] 300
m1 <- matrix(1:6, ncol=2)
length(m1)
#[1] 6