Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NUM to INT in R?

I am trying to convert numeric format to an integer in R. This is essential to a part of the project where I am using java code to run some simulations (which reads this particular data as int).

I tried both round(x$var, 0) and trunc(x$var). Both of them run successfully, but when I str(x), x$var is still num. x is a dataframe.

like image 551
Vikas Tiwari Avatar asked Jul 24 '12 19:07

Vikas Tiwari


People also ask

How do I convert a number to an int in R?

To convert a float or double to integer in R, use the as. integer() function. The as. integer() is an inbuilt function used for an object of class ursaRaster that truncates the decimal part of image values and then converts to type integer.

How do I convert numeric to data type in R?

To convert a column to numeric in R, use the as. numeric() function. The as. numeric() is a built-in R function that returns a numeric value or converts any value to a numeric value.

Is INT and NUM in R the same?

Basically,numeric class can contain both integers and floating numbers but integer class can contain only integers.

How do I convert a char to an integer in R?

Convert a Character Object to Integer in R Programming – as. integer() Function. as. integer() function in R Language is used to convert a character object to integer object.


2 Answers

Use as.integer:

set.seed(1) x <- runif(5, 0, 100) x [1] 26.55087 37.21239 57.28534 90.82078 20.16819   as.integer(x) [1] 26 37 57 90 20 

Test for class:

xx <- as.integer(x) str(xx)  int [1:5] 26 37 57 90 20 
like image 57
Andrie Avatar answered Oct 07 '22 02:10

Andrie


You can use convert from hablar to change a column of the data frame quickly.

library(tidyverse) library(hablar)  x <- tibble(var = c(1.34, 4.45, 6.98))  x %>%    convert(int(var)) 

gives you:

# A tibble: 3 x 1     var   <int> 1     1 2     4 3     6 
like image 31
davsjob Avatar answered Oct 07 '22 01:10

davsjob