【发布时间】:2016-10-04 10:25:35
【问题描述】:
我知道标题有点混乱,很抱歉。 首先是一些代码来生成我们需要的数据:
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)))
好的,所以,我有一个函数 some_function,它接受一个 data.frame 和一个向量作为参数:
#Some function a data.frame and a vector as arguments
some_function=function(a_df,a_vector){
return(a_df[,a_vector])
}
我得到了一个 data.frame 列表和一个向量列表。所以我想根据它们作为 some_function 参数的位置将 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_results 的长度为 300,虽然我预计只有 100。显然,结果也不是我所期望的。有谁知道这里发生了什么以及如何解决它?
【问题讨论】: