2

I am learning R and I have an issue trying to replace na values in a data frame excluding the first 2 columns from the process. i did this:

# example data.frame 
v1<-c("a","b","c","d")
v2<-c(3,3,NA,NA)
v3<-c(1,NA,1,1)
v4<-c(1,NA,1,NA)
v5<-c(1,0,NA,NA)
df<-data.frame(v1,v2,v3,v4,v5)
df

#fal is a Matrix with only FALSE
fal <- data.frame(matrix(ncol = 2, nrow = nrow(df), FALSE))
fal

m <- cbind(fal,is.na(df[,3:5]))
df[m]<-0

So I have a Matrix with TRUE where the na has to be replaced, and I set it to 0.

df looks like that:

   v1 v2 v3 v4 v5
1  a  3  1  1  1
2  b  3 NA NA  0
3  c NA  1  1 NA
4  d NA  1 NA NA

and the matrix look like that:

   X1    X2    v3    v4    v5
1 FALSE FALSE FALSE FALSE FALSE
2 FALSE FALSE  TRUE  TRUE FALSE
3 FALSE FALSE FALSE FALSE  TRUE
4 FALSE FALSE FALSE  TRUE  TRUE

Can someone help me with that?

Frannzz
  • 103
  • 1
  • 3
  • 11
  • 1
    If you want to replace all `NA`s, you can simply do `df[is.na(df)] <- 0` – Val Jun 14 '17 at 09:33
  • This was just an example matrix, I actually have some na in the first columns that should remain there. If I try to run my code I get: Error in FUN(X[[i]], ...) : only defined on a data frame with all numeric variables – Frannzz Jun 14 '17 at 09:41
  • 2
    Better add this error message to the question. Makes your problem clearer – fzk Jun 14 '17 at 09:45

2 Answers2

3

m is not a matrix, but a data frame.

df[as.matrix(m)] <- 0
df

##   v1 v2 v3 v4 v5
## 1  a  3  1  1  1
## 2  b  3  0  0  0
## 3  c NA  1  1  0
## 4  d NA  1  0  0

Edit: or replace fal <- data.frame(matrix(ncol = 2, nrow = nrow(df), FALSE)) withfal <- matrix(ncol = 2, nrow = nrow(df), FALSE)

Aurèle
  • 12,545
  • 1
  • 31
  • 49
2

Try this:

df[,3:5][is.na(df[,3:5])] <-0
fzk
  • 443
  • 1
  • 5
  • 12