Reputation: 493
I have a dataset where each column might have some decimals which i wish to convert to integers.
structure(list(var1 = c(0.25, 1, 2), var2 = c(1, 2, 0.5)), row.names = c(NA,
3L), class = "data.frame")
var1 var2
1 0.25 1.0
2 1.00 2.0
3 2.00 0.5
I can multiply each column by a number to make them integers. Such as multiply first column by 4 and second by 2
structure(list(var1 = c(1, 4, 8), var2 = c(2, 4, 1)), row.names = c(NA,
3L), class = "data.frame")
var1 var2
1 1 2
2 4 4
3 8 1
I want to do this multiplication using code.
Upvotes: 1
Views: 78
Reputation: 15123
For generalization, suppose that your numbers are can be expressed as pretty fractions, and using @MrFlick's lcm function for vector
library(pracma)
library(MASS)
library(stringr)
lcm_vector <- function(x) Reduce(Lcm, x)
for(i in 1:ncol(df)){
x <- df[,i]
x <- fractions(x[!(x %in% x[!x%%1])])
y <- str_split(attr(x,"fracs"),"/", simplify = T)[,2]
z <- lcm_vector(as.numeric(y))
df[,i] <- z * df[,i]
}
df
var1 var2
1 1 2
2 4 4
3 8 1
For another df
,
df <- rbind(df, c(1/3, .75))
df
var1 var2
1 0.2500000 1.00
2 1.0000000 2.00
3 2.0000000 0.50
4 0.3333333 0.75
applying code above will gives
var1 var2
1 3 4
2 12 8
3 24 2
4 4 3
Upvotes: 2