Skip to contents

stm_to_numeric() converts character columns in a data frame to numeric. It attempts to convert columns where all values are valid numeric strings into numeric values.

Usage

stm_to_numeric(dat, columns = names(dat))

Arguments

dat

A data frame or matrix containing the columns to be converted.

columns

A character vector specifying the columns to be converted. Default is names(dat), meaning all columns will be considered.

Value

A data frame or matrix with the specified columns converted to numeric values.

Details

The function checks each column in the data frame. If a column is of type character and contains valid numeric strings, it is converted to numeric. Otherwise, the column remains unchanged.

Examples

df <- data.frame(
  A = c("1", "2", "3"),
  B = c("4.5", "5.5", "6.5"),
  C = c("X", "Y", "Z")
)
str(df) # look at data type column
#> 'data.frame':	3 obs. of  3 variables:
#>  $ A: chr  "1" "2" "3"
#>  $ B: chr  "4.5" "5.5" "6.5"
#>  $ C: chr  "X" "Y" "Z"

df_new <- stm_to_numeric(df)
print(df_new)
#>   A   B C
#> 1 1 4.5 X
#> 2 2 5.5 Y
#> 3 3 6.5 Z
str(df_new) # look at data type column
#> 'data.frame':	3 obs. of  3 variables:
#>  $ A: num  1 2 3
#>  $ B: num  4.5 5.5 6.5
#>  $ C: chr  "X" "Y" "Z"