1
2
3
4
5
6
7
8
9
|
> x <- 6
> if (x %% 2 == 0) {
+ print("divisible by 2")
+ } else if (x %% 3 == 0) {
+ print("divisible by 3")
+ } else {
+ print("not divisible by 2 nor by 3...")
+ }
[1] "divisible by 2"
| cs |
2019년 7월 3일 수요일
R: if문
1.
두번째(else if문) 조건이 참이더라도 첫번째(if문) 조건이 참일 경우 첫번째 then절을 실행하고 if문을 종료한다.
2019년 7월 2일 화요일
R: Rtools을 설치했는데 rstudio에서 rtools를 인식하지 못하는 경우
1
2
|
Sys.setenv(PATH = paste("rtools을 설치한 경로; ... /Rtools/bin/", Sys.getenv("PATH"), sep = ";"))
Sys.setenv(BINPREF = "rtools을 설치한 경로; .../Rtools/mingw_ 시스템 종류, 64비트 운영 체제일 경우; 64/bin/")
| cs |
위 명령어를 실행하면 rtools를 설치한 디렉토리가 환경 변수에 추가되어 rstudio에서 rtools을 인식할 수 있게 된다.
2019년 6월 21일 금요일
R: Lists
1. 리스트의 성질(1)
리스트는 벡터, 매트릭스, 데이터 프레임, 리스트 등 모든 것을 포함할 수 있다.
2. 리스트의 성질(2)
리스트는 모든 요소를 포함할 수 있다. 리스트가 포함하는 요소의 성질을 기억하기 힘들기 때문에 요소에 이름을 부여하여 효율적으로 리스트를 관리할 수 있다.
3. 리스트의 요소 선택하기
두 개의 대괄호 사이에 "열 이름"을 입력하거나([["열 이름"]]),
$ 뒤에 열 이름을 입력한다($열 이름).
대괄호를 사용할 경우 따옴표를 사용해야하고,
$을 사용할 경우 따옴표로 사용하지 않는다.
4. 리스트에 요소 추가하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
> # Vector with numerics from 1 up to 10
> my_vector <- 1:10
>
> # Matrix with numerics from 1 up to 9
> my_matrix <- matrix(1:9, ncol = 3)
>
> # First 10 elements of the built-in data frame mtcars
> my_df <- mtcars[1:10,]
>
> # Construct list with these different elements:
> my_list <- list(my_vector, my_matrix, my_df)
> my_list
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
[[2]]
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[[3]]
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
| cs |
리스트는 벡터, 매트릭스, 데이터 프레임, 리스트 등 모든 것을 포함할 수 있다.
2. 리스트의 성질(2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
> # Vector with numerics from 1 up to 10
> my_vector <- 1:10
>
> # Matrix with numerics from 1 up to 9
> my_matrix <- matrix(1:9, ncol = 3)
>
> # First 10 elements of the built-in data frame mtcars
> my_df <- mtcars[1:10,]
>
> # Adapt list() call to give the components names
> my_list <- list(vec = my_vector, mat = my_matrix, df = my_df)
>
> # Print out my_list
> my_list
$vec
[1] 1 2 3 4 5 6 7 8 9 10
$mat
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
$df
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
| cs |
리스트는 모든 요소를 포함할 수 있다. 리스트가 포함하는 요소의 성질을 기억하기 힘들기 때문에 요소에 이름을 부여하여 효율적으로 리스트를 관리할 수 있다.
3. 리스트의 요소 선택하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
> # shining_list is already pre-loaded in the workspace
>
> # Print out the vector representing the actors
> shining_list[["actors"]]
[1] "Jack Nicholson" "Shelley Duvall" "Danny Lloyd" "Scatman Crothers"
[5] "Barry Nelson"
>
> shining_list$actors
[1] "Jack Nicholson" "Shelley Duvall" "Danny Lloyd" "Scatman Crothers"
[5] "Barry Nelson"
>
> # Print the second element of the vector representing the actors
> shining_list[["actors"]][2]
[1] "Shelley Duvall"
| cs |
두 개의 대괄호 사이에 "열 이름"을 입력하거나([["열 이름"]]),
$ 뒤에 열 이름을 입력한다($열 이름).
대괄호를 사용할 경우 따옴표를 사용해야하고,
$을 사용할 경우 따옴표로 사용하지 않는다.
4. 리스트에 요소 추가하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
> # shining_list, the list containing movie name, actors and reviews, is pre-loaded in the workspace
>
> # We forgot something; add the year to shining_list
> shining_list_full <- c(shining_list, year = 1980)
> # ext_list <- c(my_list, 추가하려는 요소의 이름 = 추가하려는 요소)
>
> # Have a look at shining_list_full
> str(shining_list_full)
List of 4
$ moviename: chr "The Shining"
$ actors : chr [1:5] "Jack Nicholson" "Shelley Duvall" "Danny Lloyd" "Scatman Crothers" ...
$ reviews :'data.frame': 3 obs. of 3 variables:
..$ scores : num [1:3] 4.5 4 5
..$ sources : Factor w/ 3 levels "IMDb1","IMDb2",..: 1 2 3
..$ comments: Factor w/ 3 levels "A masterpiece of psychological horror",..: 3 2 1
$ year : num 1980
| cs |
2019년 6월 20일 목요일
R: Data frames
1. 데이터 프레임에서 subset() 함수를 사용하여 조건을 만족하는 행만 추출하기
"subset = " 뒤에 조건을 작성하면 된다.
2. order()함수를 이용하여 특정 열의 순위를 기준으로 데이터 프레임 정렬하기
1
2
3
4
5
6
7
8
|
> # planets_df is pre-loaded in your workspace
>
> # Select planets with diameter < 1
> subset(planets_df, subset = diameter < 1)
name type diameter rotation rings
1 Mercury Terrestrial planet 0.382 58.64 FALSE
2 Venus Terrestrial planet 0.949 -243.02 FALSE
4 Mars Terrestrial planet 0.532 1.03 FALSE
| cs |
"subset = " 뒤에 조건을 작성하면 된다.
2. order()함수를 이용하여 특정 열의 순위를 기준으로 데이터 프레임 정렬하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
> # planets_df is pre-loaded in your workspace
>
> # Use order() to create positions
> positions <- order(planets_df$diameter)
>
> positions
[1] 1 4 2 3 8 7 6 5
>
> # Use positions to sort planets_df
> planets_df[positions, ]
name type diameter rotation rings
1 Mercury Terrestrial planet 0.382 58.64 FALSE
4 Mars Terrestrial planet 0.532 1.03 FALSE
2 Venus Terrestrial planet 0.949 -243.02 FALSE
3 Earth Terrestrial planet 1.000 1.00 FALSE
8 Neptune Gas giant 3.883 0.67 TRUE
7 Uranus Gas giant 4.007 -0.72 TRUE
6 Saturn Gas giant 9.449 0.43 TRUE
5 Jupiter Gas giant 11.209 0.41 TRUE
| cs |
R: Factors
1. 순서형 변수
2. 팩터 레벨 이름 변경하기
3. 팩터를 포함하는 벡터 요약하기
1
2
3
4
5
6
7
|
> # Temperature
> temperature_vector <- c("High", "Low", "High","Low", "Medium")
> factor_temperature_vector <- factor(temperature_vector, order = TRUE, levels = c("Low", "Medium", "High"))
> # levels: 오름차순으로 레벨을 부여한다.
> factor_temperature_vector
[1] High Low High Low Medium
Levels: Low < Medium < High
| cs |
2. 팩터 레벨 이름 변경하기
1
2
3
4
5
6
7
8
9
10
|
> # Code to build factor_survey_vector
> survey_vector <- c("M", "F", "F", "M", "M")
> factor_survey_vector <- factor(survey_vector)
>
> # Specify the levels of factor_survey_vector
> levels(factor_survey_vector) <- c("Female", "Male")
>
> factor_survey_vector
[1] Male Female Female Male Male
Levels: Female Male
| cs |
3. 팩터를 포함하는 벡터 요약하기
1
2
3
4
5
6
7
8
9
|
> # Generate summary for survey_vector
> summary(survey_vector)
Length Class Mode
5 character character
> # 문자열 벡터를 요약하면 원소가 몇 개인지 알 수 없고 벡터의 길이와 클래스를 출력한다.
>
> # Generate summary for factor_survey_vector
> summary(factor_survey_vector)
Female Male
2 3
> # 팩터 벡터를 요약하면 원소가 몇 개인지 출력한다.
| cs |
2019년 6월 19일 수요일
R: Matrices
1. 행의 합 구하기
※ 워크스페이스에 저장된 내용 조회하기
※ 열의 합은 colSums() 함수를 사용한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
> # Construct star_wars_matrix
> box_office <- c(460.998, 314.4, 290.475, 247.900, 309.306, 165.8)
> star_wars_matrix <- matrix(box_office, nrow = 3, byrow = TRUE,
dimnames = list(c("A New Hope", "The Empire Strikes Back", "Return of the Jedi"),
c("US", "non-US")))
> # dimnames: 리스트의 첫 번째가 rownames, 두 번째가 colnames
>
> # Calculate worldwide box office figures
> worldwide_vector <- rowSums(star_wars_matrix)
>
> worldwide_vector
A New Hope The Empire Strikes Back Return of the Jedi
775.398 538.375 475.106
| cs |
※ 워크스페이스에 저장된 내용 조회하기
1
2
|
> ls()
[1] "star_wars_matrix" "star_wars_matrix2"
| cs |
※ 열의 합은 colSums() 함수를 사용한다.
2019년 5월 23일 목요일
R: 오프라인 환경에서 설치한 패키지를 로드할 때 lazy-load database 에러가 발생하는 경우
오프라인 환경에서 설치한 패키지를 다음과 같이 로드하였을 때,
다음과 같은 에러가 발생하였습니다.
lazy-load database '패키지 설치 경로/R/패키지 이름.rdb' is corrupt
해결책은 간단합니다. R 세션을 재실행해주면 됩니다. 코드는 다음과 같습니다.
또는 rstudio를 사용하고 계실 경우 Ctrl + Shift + F10을 누르시면 R 세션을 재실행합니다.
R 세션을 재실행한 뒤 다시 패키지를 로드할 경우 에러가 발생하지 않는 것을 확인할 수 있습니다.
1
|
library(패키지 이름, lib.loc = "패키지 설치 경로")
| cs |
다음과 같은 에러가 발생하였습니다.
lazy-load database '패키지 설치 경로/R/패키지 이름.rdb' is corrupt
해결책은 간단합니다. R 세션을 재실행해주면 됩니다. 코드는 다음과 같습니다.
1
|
.rs.restartR()
| cs |
또는 rstudio를 사용하고 계실 경우 Ctrl + Shift + F10을 누르시면 R 세션을 재실행합니다.
R 세션을 재실행한 뒤 다시 패키지를 로드할 경우 에러가 발생하지 않는 것을 확인할 수 있습니다.
피드 구독하기:
글 (Atom)