R에서 na를 문자열로 바꾸는 방법(예제 포함)


Tidyr 패키지의 replacement_na() 함수를 사용하여 R의 데이터 프레임 열에 있는 특정 문자열로 NA를 바꿀 수 있습니다.

 #replace NA values in column x with "missing"
df$x %>% replace_na (' none ')

또한 이 함수를 사용하여 NA를 데이터 프레임의 여러 열에 있는 특정 문자열로 바꿀 수도 있습니다.

 #replace NA values in column x with "missing" and NA values in column y with "none"
df %>% replace_na (list(x = ' missing ', y = ' none '))

다음 예에서는 이 기능을 실제로 사용하는 방법을 보여줍니다.

예 1: NA를 열의 문자열로 바꾸기

다음 코드는 NA를 데이터 프레임 열의 특정 문자열로 바꾸는 방법을 보여줍니다.

 library (tidyr)

df <- data. frame (status=c('single', 'married', 'married', NA),
                 education=c('Assoc', 'Bach', NA, 'Master'),
                 income=c(34, 88, 92, 90))

#view data frame
df

   status education income
1 single Assoc 34
2 married Bach 88
3 married <NA> 92
4 <NA> Master 90

#replace missing values with 'single' in status column
df$status <- df$status %>% replace_na (' single ')

#view updated data frame
df 

   status education income
1 single Assoc 34
2 married Bach 88
3 married <NA> 92
4 single Master 90

예 2: NA를 여러 열의 문자열로 바꾸기

다음 코드는 데이터 프레임의 여러 열에서 NA를 특정 문자열로 바꾸는 방법을 보여줍니다.

 library (tidyr)

df <- data. frame (status=c('single', 'married', 'married', NA),
                 education=c('Assoc', 'Bach', NA, 'Master'),
                 income=c(34, 88, 92, 90))

#view data frame
df

   status education income
1 single Assoc 34
2 married Bach 88
3 married <NA> 92
4 <NA> Master 90

#replace missing values with 'single' in status column
df <- df %>% replace_na (list(status = ' single ', education = ' none '))

#view updated data frame
df 

   status education income
1 single Assoc 34
2 married Bach 88
3 married none 92
4 single Master 90

추가 리소스

R에서 일부 또는 전체 NA가 있는 행을 삭제하는 방법
dplyr에서 NA를 0으로 바꾸는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다