Simon Harmel
Simon Harmel

Reputation: 1489

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

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

Upvotes: 1

Views: 261

Answers (1)

akrun
akrun

Reputation: 886938

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)

Upvotes: 1

Related Questions