Skip to contents

dta_to_numeric() takes a data frame and converts columns containing numeric values represented as strings into numeric columns. Other columns remain unchanged.

Usage

dta_to_numeric(dat)

Arguments

dat

A data frame where numeric strings in character columns should be converted to numeric.

Value

A data frame with numeric strings converted to numeric columns.

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)
a b c
1 A 4
2 B 5
3 C 6
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)
a b c
1 A 4
2 B 5
3 C 6
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