R语言 如何用字符串替换NA
在这篇文章中,我们将讨论如何在R编程语言中用字符串替换NA。NA代表不是一个数字,我们可以在数据框架中用字符串替换NA。
创建Demonestration的数据框架
# 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
输出
name subjects address
1 sravan <NA> <NA>
2 ojaswi java hyd
3 <NA> jsp tenali
4 ramesh <NA> guntur
例1:在一列中用字符串替换NA
我们可以使用replace_na()函数将特定列中的NA替换为字符串,我们必须导入tidyr包。
语法: dataframe$column_name%>% replace_na(‘string’)
其中
- dataframe是输入的数据框架
- column_name是用字符串替换的列
R程序将给定列中的NA替换为字符串
# 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
datasubjects = datasubjects %>% replace_na('python')
# replace NA with sri devi in name column
dataname = dataname %>% replace_na('sri devi')
print(data)
输出
name subjects address
1 sravan <NA> <NA>
2 ojaswi java hyd
3 <NA> jsp tenali
4 ramesh <NA> guntur
name subjects address
1 sravan <NA> <NA>
2 ojaswi java hyd
3 <NA> jsp tenali
4 ramesh <NA> guntur
例2:在多列中用字符串替换NA值
这里我们使用与上面相同的方法,但是,要在多列中替换,我们必须在一个列表函数中指定多列
语法: dataframe %>% replace_na(list(column1 = 'string', column2 = 'string',.,columnn = 'string',))
# 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 <NA> <NA>
2 ojaswi java hyd
3 <NA> jsp tenali
4 ramesh <NA> guntur
name subjects address
1 sravan <NA> <NA>
2 ojaswi java hyd
3 <NA> jsp tenali
4 ramesh <NA> guntur