R: Apply function to matrix with elements of vector as argument

感情迁移 提交于 2019-12-01 05:58:50

Mapply is definitely a possibility. This should work:

mapply(MYFUNC, x = as.data.frame(t(df)), Var = var2)

#V1        V2        V3        V4        V5        V6        V7        V8        V9       V10 
#5.0795111 2.8693537 1.8285747 1.3640238 0.8300597 0.6280441 0.7706310 0.6720132 0.5719003 0.4259674 

The issue I think you were running into is that mapply takes either vectors or lists. In R matrices aren't lists, but data.frames are. All you need to do is transpose your matrix and convert to a data.frame and then mapply should work. Each column in a data.frame is an element in the list which is why we have to transpose it (so that each row will be mapped to each element in the vector).

As there are two arguments that should be the corresponding rows and elements in matrix/vector respectively, we can loop through the sequence of rows, subset the data and apply the function

sapply(seq_len(nrow(df)), function(i) MYFUNC(df[i,], Var = var2[i]))
#[1] 5.0795111 2.8693537 1.8285747 1.3640238 0.8300597 0.6280441
#[7] 0.7706310 0.6720132 0.5719003 0.4259674

For the specific example, it can be vectorized with rowSums

rowSums(df)/var2
#[1] 5.0795111 2.8693537 1.8285747 1.3640238 0.8300597 0.6280441 
#[7] 0.7706310 0.6720132 0.5719003 0.4259674
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!