R Change NA values

拜拜、爱过 提交于 2019-11-27 06:58:16

问题


My data looks like this: http://imgur.com/8KgvWvP

I want to change the values NA to another value for each column. For example in the column that contains NA, Single and Dual, I want to change all the NA to 'Single'.

I tried this code:

data_price$nbrSims <- ifelse(is.na(data_price$nbrSims), 'Single', data_price$nbrSims)

But then my data looks like this, where Dual became 2 and Single 1. http://imgur.com/TC1bIgw

How can I change the NA values, without changing the other values? Thanks in advance!


回答1:


Try this (check which are NA and than replace them with "Single"):

data_price$nbrSims <- as.character(data_price$nbrSims)
data_price$nbrSims[is.na(data_price$nbrSims)] <- "Single"



回答2:


The reason why we got integer values 1 and 2 after the ifelse statement is because the column is a factor class. We convert it to character class and it should work fine

 data_price$nbrSims <- as.character(data_price$nbrSims)
 data_price$nbrSims <- ifelse(is.na(data_price$nbrSims), 
             'Single', data_price$nbrSims)



回答3:


Just to be clear, Marta's answer is right.

You can also change all Na Values with this

data_price[is.na(data_price)]<-"Something"


来源:https://stackoverflow.com/questions/34718771/r-change-na-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!