![](/img/trans.png)
[英]How to use lapply with a function that requires a vector as an argument
[英]How to modify the list/vector argument in place in the R function lapply?
也許是一個奇怪的問題,但我有一個真正的用例:是否可以就地修改,即當函數運行而不是在副本上時,R 中lapply
函數中的列表/向量參數? 如果是,該怎么做? 由於一些(預期的)副作用,我需要它。 更具體地說,在 list/vector 參數的每個元素都被lapply
'read'(或'used') lapply
,我需要刪除它。
此致,
奧利維爾
一些代碼來說明我在尋找什么。
Blocked
是一個原子向量, B
是一個列表。
Unblock <- function(M)
{
Blocked[M] <<- FALSE
Length_B_M <- length(B[[M]])
if(Length_B_M > 0)
{
# Vectorised version
UnblockAndUpdateAdjacencyList <- function(Node.Value)
{
Node.Name <- as.character(Node.Value)
Node.Value <<- NULL # This is not correct because it won't delete the argument in place
if(Blocked[Node.Name]) Unblock(Node.Name)
}
lapply(X = B[[M]], FUN = UnblockAndUpdateAdjacencyList)
# Unvectorised version
# 'i' is a vector/list index - integer
# Important: it is necessary to browse items backwards as items from the atomic vector 'B[[M]]' are deleted and thus its length decreases at each iteration
for(i in Length_B_M:1)
{
P <- as.character(B[[M]][i])
B[[M]] <<- B[[M]][-i]
if(Blocked[P]) Unblock(P)
}
}
}
實際上,我找到了一個有點優雅的解決方案,即在lapply
的參數中沒有任何顯式循環和向量/列表的任何副本。
Unblock <- function(M)
{
Blocked[M] <<- FALSE
Length_B_M <- length(B[[M]])
if(Length_B_M > 0)
{
# Vectorised version
# One solution is to copy the vector/list in the argument of 'lapply' - Actually not even needed
UnblockAndUpdateAdjacencyList <- function(Node.Value)
{
Node.Name <- as.character(Node.Value)
B[[M]] <<- B[[M]][-1]
if(Blocked[Node.Name]) Unblock(Node.Name)
}
#B_M_copy <- B[[M]]
#lapply(X = B_M_copy, FUN = UnblockAndUpdateAdjacencyList)
lapply(X = B[[M]], FUN = UnblockAndUpdateAdjacencyList)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.