Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a character string to the same type as another object

Tags:

r

I have a character string, and I want to convert it to the same type as another object. You can assume this object is a vector. For example, given a string "50", and a target vector 1:10, I want "50" to be converted to an integer 50. I wonder if there is a generic way to do the conversion. It is simple if I know which type I want to convert it to, e.g. I can use as.numeric() if I want it to be a number.

The background of this question is: I want to provide a graphical user interface so users can edit a value in a table. After they edit a cell, I will get a character string, and I know the original data (typically a matrix or a data frame). I want to update the original data with this new value. I cannot simply do data[i, j] <- value because value is a character string.

I could enumerate a few most common types (e.g. numeric, character, factor, date, ...) and use as.*() to do the conversion, but I'd prefer not to go this way if there is an existing generic approach. Things can be a little tricky for dates (timezone, origin) and factors (may add a new level).

like image 523
Yihui Xie Avatar asked Jan 19 '26 03:01

Yihui Xie


1 Answers

(You might have found a way to solve this by now, but I'd have a try anyway...)

I checked the R documentation, and found that base::as(object, Class) is the generic way to do so. However, the default coercion methods are limited, and currently there is no default method to coerce Character class to Date class, nor for Factor class (you could check all the existing methods by methods::showMethods("coerce"). However, you could set customised methods with methods::setAs(), which is beyond my ability.

With my limited programming knowledge, I would probably use the following way to handle this problem:

assign_target_class = function (input_vector, target_vector){
    is.date = function(x) inherits(x, 'Date')
    if (is.date(target_vector)) {vector_class <- 'Date'}
    else if (base::is.factor(target_vector)) {vector_class <- 'Factor'}
    else {vector_class <- class(target_vector)}
    input_vector = as(input_vector, vector_class)
    input_vector
  }

P.S. if the date variable of the target vector is not set as Date yet, we could replace is.date with this argument instead:

is.convertible.to.date <- function(x) !is.na(as.Date(as.character(x), 
    tz = 'UTC', format = '%Y-%m-%d'))
like image 179
yihan Avatar answered Jan 20 '26 18:01

yihan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!