Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading