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