1000개의 무작위 균일 난수를 입력으로 제공받은 함수를 호출
# 임의의 무작위 데이터를 생성
l = replicate(20, rnorm(sample(1:10, 1), mean=0, sd=1), simplify=FALSE)
# for 루프로 작성
out = vector("list", length(l))
for (i in seq(l)) {
out[[i]] = length(l[[i]])
}
unlist(out)
## [1] 5 4 5 9 10 3 5 3 3 9 1 10 9 5 8 9 2 9 10 9
# lapply로 작성
unlist(lapply(l, length))
## [1] 5 4 5 9 10 3 5 3 3 9 1 10 9 5 8 9 2 9 10 9
data.frame에 lapply 적용하기
# 평균(mean)으로 각 열을 나눔
mtcars[] = lapply(mtcars, function(x){
x/mean(x) # x에는 data.frame의 각 열이 들어옴
})
for문 사용
xs = runif(1e4)
res = c()
# 첫번째 방법
for (x in xs) {
res = c(res, sqrt(x))
}
res = numeric(length(xs)) # numeric : 길이만큼 0벡터 만듬
for (i in seq(xs)) {
res[i] = sqrt(xs[i])
}
lapply로 구현하기
xs = runif(1e4)
ret = unlist(lapply(xs, function(x){
sqrt(x)
}))
ret[1:10]
## [1] 0.4223976 0.5768065 0.9410556 0.2452229 0.8626159 0.9631699 0.5534060
## [8] 0.6318466 0.8488031 0.8736057
res = numeric(length(xs))
ret = unlist(lapply(seq(xs), function(i){
res[i] = sqrt(xs[i])
}))
ret[1:10]
## [1] 0.4223976 0.5768065 0.9410556 0.2452229 0.8626159 0.9631699 0.5534060
## [8] 0.6318466 0.8488031 0.8736057
'R > functional' 카테고리의 다른 글
data_frame, apply (0) | 2018.06.07 |
---|---|
parallelize (0) | 2018.06.06 |