简体   繁体   中英

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

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 ie c(1, 0, 'a') which remains as character because of the type precedence

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM