0 votes
1 view
in R Programming by (5.3k points)

How do you convert a data frame column to a numeric type?

1 Answer

0 votes
by (25.3k points)

You can convert a data frame column to a numeric type as follows:

as.numeric(as.character(data_frame$column_name))

For example:

df <- data.frame(char = letters[1:3], fake_char = as.character(1:3), fac = factor(1:3), char_fac = factor(letters[1:3]), num = 1:3, stringsAsFactors = FALSE) df$new <- as.numeric(as.character(df$fake_char)) df

Output:

  char fake_char fac char_fac num new

1     a       1     1       a   1   1

2     b       2     2       b   2   2

3     c       3     3       c   3   3

To check the class of the converted variable:

lapply(df,class) 

$char 

[1] "character" 

$fake_char 

[1] "character" 

$fac 

[1] "factor" 

$char_fac 

[1] "factor" 

$num 

[1] "integer" 

$new 

[1] "numeric"

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...