Re: [问题] apply 取代for

楼主: celestialgod (天)   2018-03-29 23:35:04
※ 引述《disney82231 (小刀会序曲)》之铭言:
: [问题类型]:
: 程式咨询(我想用R 做某件事情,但是我不知道要怎么用R 写出来)
:
: [软件熟悉度]:
: 入门(写过其他程式,只是对语法不熟悉)
: [问题叙述]:
: 用for 写了一个循环,想用apply写出一样的结果
: 另外想请问,在多数情况下,apply都能取代for吗
: [程式范例]:
: for (i in 2:10){
: x$v1[x[,i]==1] <- i }
: }
: 若每列x的第i行=1时,x每列的第一行改成i
: [关键字]:
: apply for
测试了一下我原本预想的方法,发现用for就很快了XDDD
然后回一下,像这种case,其实用apply是不适合的
基本上直接去修改原本的值是最简单的
library(data.table)
## random generation
x <- matrix(rbinom(1e6, 3, 0.5), 1e5)
# check dimension of x
dim(x) # 100000, 10
## copy x
x2 <- x
## for-loop method
st <- proc.time()
for (i in 2:10)
x2[x2[ , i] == 1, ] <- i
proc.time() - st
# user system elapsed
# 0.02 0.00 0.01
## vectorized method
st <- proc.time()
# get indices which is equal to 1 in column 2 to 10
idxDT <- data.table(which(x[ , 2:10] == 1, arr.ind = TRUE))
# calculate what the value at i-th location will change to
out <- idxDT[ , .(value = min(col) + 1), by = .(row)]
# assign the values
x[out$row, ] <- out$value
proc.time() - st
# user system elapsed
# 0.12 0.01 0.14
## check equality
all.equal(x, x2) # TRUE
: > sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
作者: obarisk (OSWALT)   2018-03-30 05:34:00
用diag会更快吗idx = diag(x1) == 1x1$v1[2:nrow(x1)] <- ifelse(idx[2:nrow(x1)], 2:nrow(x1), x1$v1[-1])

Links booklink

Contact Us: admin [ a t ] ucptt.com