【问题标题】:Second argument of the mapply inside function as a vector in Rmapply inside 函数的第二个参数作为 R 中的向量
【发布时间】: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。显然,结果也不是我所期望的。有谁知道这里发生了什么以及如何解决它?

【问题讨论】:

    标签: r list vector mapply


    【解决方案1】:

    我们需要使用Map

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

    或者mapply 和SIMPLIFY = FALSE

    r2 <- mapply(function(x,y) x[,y], list_of_df, list_of_vector, SIMPLIFY=FALSE)
    length(r2)
    #[1] 100
    

    Map 只是mapply 的包装器,带有SIMPLIFY=FALSE 选项。发生的情况是当对象尺寸相同时,它会简化为mapply 的矩阵,因为默认选项是SIMPLIFY = TRUE

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

    matrix 的 length 是其维度的乘积,即

    m1 <- matrix(1:6, ncol=2)
    length(m1)
    #[1] 6
    

    【讨论】:

    • 哇太棒了!打扰一下,我知道我可以在 Google 上进行搜索,但由于您可能会胜任,您能告诉我什么是 wrapper 吗?我一直无法理解。
    • @hansglick 只需在您的控制台上输入Map 它会给出function (f, ...) { f &lt;- match.fun(f) mapply(FUN = f, ..., SIMPLIFY = FALSE) }
    猜你喜欢
    • 2019-05-15
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2021-12-28
    • 1970-01-01
    • 2021-07-03
    • 2023-03-19
    相关资源
    最近更新 更多