[SOLVED] Converting numeric character vectors to numeric leaving non-numeric character vectors unchanged in data.frame

Issue

In data below, all variables (columns) are character strings. However, some of them are real character strings (Z), others are in reality numeric vectors that have been forced into a character string (N).

In general (data below is obviously is toy), how can I return variables like N into numeric but leave other variables like Z unchanged?

data <- data.frame(Z = letters[1:3], N = as.character(-1:1))

Solution

If this needs to be automatic, use type.convert which picks up the column type based on the values and return the appropriate type. Note that this may not work if there are any values in the column have mixed type i.e. c(1, 0, 'a') which remains as character because of the type precedence

type.convert(data, as.is = TRUE)

Answered By – akrun

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published.