Search code examples
rvectorcharacternumericcoerce

R coerce character vector into character and numeric


I have a vector:

 > vek
[1] "0"    "0"    "NULL" "0"    "0"    "0"    "0"   "NULL"

I want to coerce vector into numeric, where is numer and string, where is string

> vek
[1] 0    0    "NULL"  0    0    0    0   "NULL"

Is it possible? How can I manage that?


Solution

  • You cannot have elements of different types in the same vector. But you can do it in a list. Maybe you could transform your vector in list direclty.

    vekl <- as.list(vek)
    
    for (i in 1: length(vekl)){
      temp <- as.numeric(vekl[[i]])
      if (! is.na(temp))
        vekl[[i]] <- temp
    }
    

    To avoid warnings, use this: suppressWarnings( temp <- as.numeric(vekl[[i]]) ). It ignores all warnings so you have to pay attention when you use this function...