Skip to content
Prev 310916 / 398502 Next

using ifelse to remove NA's from specific columns of a data frame containing strings and numbers

HI,

But, this replace second column NAs to 1.? May be, the na.replace() should be applied to df1[,-1]

df1<-read.table(text="
col1 col2 col3
A?? 15.5?? 8.5
A?? 8.5??? 7.5
A?? NA???? NA
B?? 8.0?? 6.0
B?? NA???? NA
B?? 9.0?? 10.0
",sep="",header=TRUE,stringsAsFactors=FALSE)
df2<-df1[,-1]
na.replace<-seq(1:ncol(df2))-1
df2[,names(df2)]<-sapply(1:dim(df2)[2],function(ii){ifelse(is.na(df2[,ii]),na.replace[ii],df2[,ii])})
df2$col1<-df1$col1
df2[order(names(df2))]
#? col1 col2 col3
#1??? A 15.5? 8.5
#2??? A? 8.5? 7.5
#3??? A? 0.0? 1.0
#4??? B? 8.0? 6.0
#5??? B? 0.0? 1.0
#6??? B? 9.0 10.0
A.K.





----- Original Message -----
From: soon yi <soon.yi at ymail.com>
To: r-help at r-project.org
Cc: 
Sent: Thursday, November 15, 2012 2:29 PM
Subject: Re: [R] using ifelse to remove NA's from specific columns of a data frame containing strings and numbers

#Data
df<-data.frame(id=letters[1:10],var1=rnorm(10,10,5),var2=rnorm(10,5,2),var3=rnorm(10,1,1))
#Missing
df$var1[2]<-df$var2[c(2,6)]<-df$var3[c(2,5)]<-NA

na.replace<-seq(1:ncol(df))-1

df[,names(df)]<-sapply(1:dim(df)[2], function(ii)
{ifelse(is.na(df[,ii]),na.replace[ii],df[,ii])} )




David Romano-2 wrote

            
--
View this message in context: http://r.789695.n4.nabble.com/using-ifelse-to-remove-NA-s-from-specific-columns-of-a-data-frame-containing-strings-and-numbers-tp4649599p4649642.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.