如何在 r 中用字符串替换 na(附示例)


您可以使用Tidyr包中的Replace_na()函数将 NA 替换为 R 中数据帧列中的特定字符串:

 #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

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注