vitor
vitor

Reputation: 1250

how to multiply all decimals in a data frame by a constant?

data <- data.frame(id = c("10001", "10002", "10003", "10004"), V1 = c(10,11,15,9.3), V2 = c(5,7,21,30.2), V3 = c(10.3, 11, 19, 12))
> data
    id   V1   V2   V3
1 10001 10.0  5.0 10.3
2 10002 11.0  7.0 11.0
3 10003 15.0 21.0 19.0
4 10004  9.3 30.2 12.0

How can I multiply all decimals by 100 and make the data look like this:

> data
    id    V1   V2     V3
1 10001   10    5   1030
2 10002   11    7     11
3 10003   15   21     19
4 10004  930 3020     12

Upvotes: 2

Views: 3049

Answers (4)

Jilber Urbina
Jilber Urbina

Reputation: 61154

Here's one approach:

> index  <- data[, -1] %% 1 != 0
> data[, -1][index] <- data[, -1][index] *100 
> data
     id  V1   V2   V3
1 10001  10    5 1030
2 10002  11    7   11
3 10003  15   21   19
4 10004 930 3020   12

Upvotes: 3

Matthew Plourde
Matthew Plourde

Reputation: 44614

Another way:

d.m <- data.matrix(data)
decs <- as.integer(d.m) != d.m
data[decs] <- d.m[decs] * 100
#      id  V1   V2   V3
# 1 10001  10    5 1030
# 2 10002  11    7   11
# 3 10003  15   21   19
# 4 10004 930 3020   12

Upvotes: 2

Blue Magister
Blue Magister

Reputation: 13363

Use the modulo function %% to find the entries with decimal parts.

Beware floating-point approximation error.

data.frame(lapply(data, function(x) {
    if(is.numeric(x)) {
        x[x %% 1 > 0] <- x[x %% 1 > 0] * 100
        return(x)
    } else return(x)
}))

Upvotes: 1

James
James

Reputation: 66834

sapply along the numeric columns and use ifelse to multiply any elements with a fractional part, then cbind the first column of the original data with this:

cbind(data[1],sapply(data[-1],function(x) ifelse(x%%1,x*100,x)))
     id  V1   V2   V3
1 10001  10    5 1030
2 10002  11    7   11
3 10003  15   21   19
4 10004 930 3020   12

Upvotes: 7

Related Questions