Home > front end >  Converting numeric character vectors to numeric leaving non-numeric character vectors unchanged in d
Converting numeric character vectors to numeric leaving non-numeric character vectors unchanged in d

Time:03-15

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))

CodePudding user response:

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)
  • Related