我需要從R中的每個列表元素中減去指定的值。在this文章中提到,對於這樣的任務,使用apply
系列函數代替循環。我試過以下:減去R中每個列表元素的值
# Define list
> a = 1:20
# Substraact this from each element
> substract_me = 5
# Function for substracting
> substract = function(x,y) { ret = x-y; return(ret) }
# The problem is that I do not know how to access the current array element and pass it to substract function
lapply(a, substract)
Here提及的是,匿名函數也可以使用,但它並沒有爲我工作,我得到語法錯誤。事實上,它看起來就像句法糖。這個問題仍然是相同的,那我需要一些佔位符或東西時,我使用lapply
功能,這樣我就可以訪問當前列表元素:
lapply(a, function([WHAT TO ADD HERE???],substract_me) substract([WHAT TO ADD HERE???],substract_me))
Here的東西可能有關,但我並沒有弄清楚的東西,從如何工作的發佈代碼片段。
'了'不是'list'。嘗試'typeof(a)'或'class(a)'。 –