简体   繁体   中英

How to use apply() with arithmetic functions (R)

In R, how do I use apply with arithmetic functions? For example, given an m-by-n matrix U, with columns c_1, c_2, ..., c_n, I want to perform the following operation on each column c_i:

for each element u in c_i,

u<-u+min(c_i)*sign(min(c_i))*1.05

这是你想要的:

apply(U, 2, function(c_i) { c_i + min(c_i)*sign(min(c_i))*1.05 })

I know that you asked for the answer in regard to apply , however, I thought I would include another approach which may be slightly faster.

library(matrixStats)
U + abs(colMins(U))[col(U)] * 1.05

@Sam Dickson, thanks for pointing out that abs(min(c_i)) is the same as min(c_i)*sign(min(c_i))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM