R에서 경고를 억제하는 방법(예제 포함)
다음 방법을 사용하여 R에서 경고를 억제할 수 있습니다.
방법 1: 특정 줄의 경고 제거
suppressWarnings(one line of code)
방법 2: 전역적으로 경고 제거
suppressWarnings({ several lines of code just a bunch of code lots and lots of code })
다음 예제에서는 두 개의 경고 메시지를 생성하는 다음 코드를 통해 실제로 각 메서드를 사용하는 방법을 보여줍니다.
#define character vector x <- c('1', '2', '3', NA, '4', 'Hey') #convert to numeric vector x_numeric <- as. numeric (x) #display digital vector print (x_numeric) Warning message: NAs introduced by coercion [1] 1 2 3 NA 4 NA #define two vectors a <- c(1, 2, 3, 4, 5) b <- c(6, 7, 8, 9) #add the two vectors a+b [1] 7 9 11 13 11 Warning message: In a + b: longer object length is not a multiple of shorter object length
방법 1: 특정 줄의 경고 제거
as.numeric( ) 함수 주위에 억제Warnings( ) 함수를 래핑하여 코드에서 첫 번째 경고만 억제할 수 있습니다.
#define character vector x <- c('1', '2', '3', NA, '4', 'Hey') #convert to numeric vector suppressWarnings(x_numeric <- as.numeric (x)) #display digital vector print (x_numeric) [1] 1 2 3 NA 4 NA #define two vectors a <- c(1, 2, 3, 4, 5) b <- c(6, 7, 8, 9) #add the two vectors a+b [1] 7 9 11 13 11 Warning message: In a + b: longer object length is not a multiple of shorter object length
첫 번째 경고 메시지는 더 이상 나타나지 않지만 두 번째 경고 메시지는 계속 나타납니다.
방법 2: 전역적으로 경고 제거
모든 경고를 전역적으로 억제하기 위해 전체 코드 부분에 억제Warnings({}) 함수를 래핑할 수 있습니다.
suppressWarnings({ #define character vector x <- c('1', '2', '3', NA, '4', 'Hey') #convert to numeric vector suppressWarnings(x_numeric <- as.numeric (x)) #display digital vector print (x_numeric) [1] 1 2 3 NA 4 NA #define two vectors a <- c(1, 2, 3, 4, 5) b <- c(6, 7, 8, 9) #add the two vectors a+b [1] 7 9 11 13 11 })
전체 코드 부분에 억제Warnings({}) 함수를 래핑했기 때문에 이번에는 경고가 표시되지 않습니다.
추가 리소스
다음 튜토리얼에서는 R에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
경고 R을 피하는 방법: getOption(“max.print”)에 도달함
R 경고 처리 방법: glm.fit: 알고리즘이 수렴되지 않았습니다.
해결 방법: 런타임 경고: double_scalars에서 잘못된 값이 발견되었습니다.