Learn R Programming

wrMisc (version 1.2.3)

convToNum: Convert to numeric

Description

convToNum checks if input vector/character string contains numbers (with or without comma) and attempts converting to numeric. This functions was designed for extracting the numeric part of character-vectors (or matrix) containing both numbers and character-elements. Depending on the parameters convert and remove text-entries can be converted to NA (in resulting numeric objects) or removed (the number of elements/lines gets reduced, in consequece). Note: if 'x' is a matrix, its matrix-dimensions & -names will be preseved. Note: so far Inf and -Inf do not get recognized as numeric.

Usage

convToNum(
  x,
  spaceRemove = TRUE,
  convert = c(NA, "sparseChar"),
  remove = NULL,
  euroStyle = TRUE,
  sciIncl = TRUE,
  callFrom = NULL,
  silent = TRUE
)

Arguments

x

vector to be converted

spaceRemove

(logical) to remove all heading and trailing (white) space (until first non-space character)

convert

(character) define which type of non-conform entries to convert to NAs. Note, if remove is selected to eliminate character-entries they cannot be converted any more. Use 'allChar' for all character-entries; 'sparseChar' sparse (ie rare) character entries; NA for converting 'Na' or 'na' to NA; if 'none' or NULL no conversions at all.

remove

(character) define which type of non-conform entries to remove, removed items cannot converted to NA any more. Use 'allChar' for removing all character entries; NA for removing all instances of NA (execept thise created by converting text); all elements will be kept if 'none' or NULL.

euroStyle

(logical) if TRUE will convert all ',' (eg used as European decimal-separator) to '.' (as internally used by R as decimal-separator), thus allowing converting the European decimal format.

sciIncl

(logical) include recognizing scientific notation (eg 2e-4)

callFrom

(character) allow easier tracking of message(s) produced

silent

(logical) suppress messages

Value

numeric vector (or matrix (if 'x' is matrix))

See Also

numeric

Examples

Run this code
# NOT RUN {
x1 <- c("+4"," + 5","6","bb","Na","-7") 
convToNum(x1,convert=c("allChar"))
convToNum(x1)        # too many non-numeric instances for 'sparseChar'

x2 <- c("+4"," + 5","6","-7"," - 8","1e6","+ 2.3e4","-3E4","- 4E5") 
convToNum(x2,convert=NA,remove=c("allChar",NA))
convToNum(x2,convert=NA,remove=c("allChar",NA),sciIncl=FALSE)
# }

Run the code above in your browser using DataLab