如何用 R 中的字符串替换 NA?
在本文中,我们将讨论如何在 R 编程语言中用字符串替换 NA。 NA 代表 Not a Number,我们可以将 NA 替换为数据框中的字符串。
为演示创建数据框:
R
# create a dataframe
data = data.frame(name = c("sravan","ojaswi",NA,"ramesh"),
subjects = c(NA,"java","jsp",NA),
address = c(NA,"hyd","tenali","guntur"))
# display
data
R
# load the library
library("tidyr")
# create a dataframe
data = data.frame(name = c("sravan","ojaswi",NA,"ramesh"),
subjects = c(NA,"java","jsp",NA),
address = c(NA,"hyd","tenali","guntur"))
# display
print(data)
# replace NA with python in subjects column
data$subjects = data$subjects %>% replace_na('python')
# replace NA with sri devi in name column
data$name = data$name %>% replace_na('sri devi')
print(data)
R
# load the library
library("tidyr")
# create a dataframe
data = data.frame(name = c("sravan","ojaswi",NA,"ramesh"),
subjects = c(NA,"java","jsp",NA),
address = c(NA,"hyd","tenali","guntur"))
# display
print(data)
# replace NA with python in subjects
# column and sri devi in name column
data = data %>% replace_na(list(subjects='python', name='sri devi'))
print(data)
输出:
name subjects address
1 sravan
2 ojaswi java hyd
3 jsp tenali
4 ramesh guntur
示例 1:将 NA 替换为一列中的字符串
我们可以使用 replace_na()函数将 NA 替换为特定列中的字符串,我们必须导入 tidyr 包
Syntax: dataframe$column_name%>% replace_na(‘string’)
where
- dataframe is the input dataframe
- column_name is the column replace with the string
R程序用给定列中的字符串替换NA
R
# load the library
library("tidyr")
# create a dataframe
data = data.frame(name = c("sravan","ojaswi",NA,"ramesh"),
subjects = c(NA,"java","jsp",NA),
address = c(NA,"hyd","tenali","guntur"))
# display
print(data)
# replace NA with python in subjects column
data$subjects = data$subjects %>% replace_na('python')
# replace NA with sri devi in name column
data$name = data$name %>% replace_na('sri devi')
print(data)
输出:
name subjects address
1 sravan
2 ojaswi java hyd
3 jsp tenali
4 ramesh guntur
name subjects address
1 sravan
2 ojaswi java hyd
3 jsp tenali
4 ramesh guntur
示例 2:用多列中的字符串替换 NA
这里我们使用与上面相同的方法,但是,要替换多个列,我们必须在列表函数中指定多个列
Syntax: dataframe %>% replace_na(list(column1 = ‘string’, column2 = ‘string’,.,columnn = ‘string’,))
R
# load the library
library("tidyr")
# create a dataframe
data = data.frame(name = c("sravan","ojaswi",NA,"ramesh"),
subjects = c(NA,"java","jsp",NA),
address = c(NA,"hyd","tenali","guntur"))
# display
print(data)
# replace NA with python in subjects
# column and sri devi in name column
data = data %>% replace_na(list(subjects='python', name='sri devi'))
print(data)
输出:
name subjects address
1 sravan
2 ojaswi java hyd
3 jsp tenali
4 ramesh guntur
name subjects address
1 sravan
2 ojaswi java hyd
3 jsp tenali
4 ramesh guntur