Convert numeric strings in a data frame or tibble to numeric numbers
Source:R/dta_to_numeric.R
dta_to_numeric.Rd
dta_to_numeric()
takes a data frame and converts columns containing
numeric values represented as strings into numeric columns. Other columns
remain unchanged.
Details
The function scans each column in the input data frame. For character
columns, it checks if all the values can be safely coerced to numeric.
If so, the column is converted to numeric using as.numeric()
.
Non-character columns or character columns containing non-numeric values
remain unchanged.
Columns are processed using lapply()
, which ensures efficient
handling of each column.
Examples
# A data frame with numeric character (a), characters (b) and numeric numbers (c)
df <- data.frame(
a = c("1", "2", "3"),
b = c("A", "B", "C"),
c = c(4, 5, 6)
)
dta_gtable(df)
str(df)
#> 'data.frame': 3 obs. of 3 variables:
#> $ a: chr "1" "2" "3"
#> $ b: chr "A" "B" "C"
#> $ c: num 4 5 6
# Convert numeric strings to numeric columns
df <- dta_to_numeric(df)
dta_gtable(df)
str(df)
#> tibble [3 × 3] (S3: tbl_df/tbl/data.frame)
#> $ a: num [1:3] 1 2 3
#> $ b: chr [1:3] "A" "B" "C"
#> $ c: num [1:3] 4 5 6