Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

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

1 Answer

0 votes
by

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"

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...