Convert character columns to numeric
stm_to_numeric.Rd
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))
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"