Search code examples
r-factor

how to add a new factor in R


I have a data frame:

a <- c("",1,2,3,2,2,1,3,"")
b <- c(1,2,3,4,5,3,8,2,8)
a1 <- as.factor(a)
f <- data.frame(x=a1,y=b)
f
 x y
1   1
2 1 2
3 2 3
4 3 4
5 2 5
6 2 3
7 1 8
8 3 2
9   8

the x column is a factor, but I want add a factor "0" to the null place,for example, I want use if(is.na(f$x)) f$x <- 0,but it shows warnings:

Warning message:
In if (is.na(f$x)) f$x  1 and only the first element will be used

and I use:

for(i in 1:nrow(f)){
 if(is.na(f$x[i])){
     f$x[i] <- 0
 }
}

but it has nothing to do.How can I tackle this problem? Thank you for your help!


Solution

  • You dont need a for loop, a quicker way is by

    a <- c("",1,2,3,2,2,1,3,"")
    > b <- c(1,2,3,4,5,3,8,2,8)
    > a1 <- as.factor(a)
    > f <- data.frame(x=a1,y=b)
    > 
    > f$x <- ifelse(f$x=="",0,f$x)
    > f$x
    [1] 0 2 3 4 3 3 2 4 0
    > f$x <- as.factor(f$x)
    > str(f)
    'data.frame':   9 obs. of  2 variables:
     $ x: Factor w/ 4 levels "0","2","3","4": 1 2 3 4 3 3 2 4 1
     $ y: num  1 2 3 4 5 3 8 2 8