Change type of object based on typeof another object

Viewed 1188


How do I change the typeof of one object a to another object b without explicitly specifying the type

a <- letters
b <- as.factor(a)

typeof(a)
#> [1] "character"

So I would like to convert b to typeof(a), but without explicitly using as.character, because in another instance a might be e.g. integer. This obviously does not work:

typeof(b) <- typeof(a)
2 Answers

The closest I could come is, but not sure if there's any better solution.

a <- '1'

b <- 2

a <- unlist(lapply(a,paste0('as.',class(b))))

a

a <- '245'

a <- unlist(lapply(a,paste0('as.',class(b))))

a

Output:
> a
[1] 245

Similar answer to @amrrs except I think you may want this functionality to be used programtically, and when converting types of an object you may get errors that return NA's - which is unwanted behaviour - when you try and convert variables that cannot be coerced to another data type.

The below function accounts for this based on R's coercion rules. (Assuming you want to be using class() and not typeof())

convertClass <- function(object1, object2){
  logic=c("logical", "integer", "numeric", "complex", "character", "list")

  ifelse(match(class(object1), logic) < match(class(object2), logic),
         eval(parse(text=paste0('as.',class(object2),"(",object1,")"))),
         paste0("convertClass() cannot convert type ", class(object1), " to ", class(object2))
    )
  }

> convertClass(1,'1')
[1] "1"
> convertClass('1', 1)
[1] "convertClass() cannot convert type character to numeric"

Using this loses the functionality of converting "1" to 1 for example, which can be coerced in R, but does provide a strict safeguard if you don't know the type of a variable that you are feeding the function.

Related