데이터 분석/R 데이터 처리 & 분석

[R] rep 함수 (반복적으로 값 산출하기)

love R 2022. 7. 3. 03:55
반응형

rep 함수 (반복적으로 값 산출하기)

 

숫자나 문자열을 반복적으로 산출하는 작업 시에는 rep 함수를 사용합니다.

 

1. rep 함수

 

2.  rep 함수 예시(숫자형)

1) 3을 5회 반복
rep
(x=3, times=5)
[1]  3 3 3 3 3



2) 1~3을 4회 반복

rep(x=1:3, times=4)
[1] 1 2 3 1 2 3 1 2 3 1 2 3



3) 1~3의 각 요소를 4회씩 반복

rep(x=1:3, each=4)
[1] 1 1 1 1 2 2 2 2 3 3 3 3 



4) 1~3의 각 요소를 4회씩 반복 & 전체를 3회 반복

rep(x=1:3, each=4, times=3)
[1] 1 1 1 1 2 2 2 2 3 3 3 3 1 1 1 1 2 2 2 2 3 3 3 3 1 1 1 1 2 2 2 2 3 3 3 3



5) 1~3의 각 요소를 4회씩 반복 & 전체를 3회 반복 & 길이를 22으로 맞춤
test <- rep(x=1:3, each=4, times=3, lengh.out=22)
test
[1] 1 1 1 1 2 2 2 2 3 3 3 3 1 1 1 1 2 2 2 2 3 3

length(test)
[1] 22


 

 

3.  rep 함수 예시(문자형)

1) 문자형 벡터 반복
rep(x=c("one","two","three"), times=4)
 [1] "one"   "two"   "three" "one"   "two"   "three" "one"   "two"   "three"  "one"   "two"   "three"

2) 문자형 벡터 각 요소를 반복
rep(x=c("one","two","three"), each=3)
[1] "one"   "one"   "one"   "two"   "two"   "two"   "three" "three" "three"

3) 문자형 벡터 각 요소를 2회 반복 & 전체를 4회 반복
rep
(x=c("one","two","three"), each=2, times=4)
 [1] "one"   "one"   "two"   "two"   "three" "three" "one"   "one"   "two"   "two"   "three" "three" "one"   "one"  
[15] "two"   "two"   "three" "three" "one"   "one"   "two"   "two"   "three" "three"

4) 문자형 벡터 각 요소를 2회 반복 & 전체를 3회 반복 & 길이를 15으로 맞춤
test <- rep(x=c("one","two","three"), each=2, times=3, length.out=15)
test
 [1] "one"   "one"   "two"   "two"   "three" "three" "one"   "one"   "two"   "two"   "three" "three" "one"   "one"  
[15] "two"   

length(test)
[1] 15

 

 

 

반응형