ravi
ravi

Reputation: 1088

In R how to round conditional on each element?

Following is the example data table.

I want to conditionally round any element more than 60 to 2 decimal place without using for loop!

x <- data.frame(c1=c(1,2,3,8,1,300.234),
                c2=c(5.234,5,6,3,3.1,4.233),
                c3=c(7,6,8,4.3,2,60.191),
                c4=c(4,1,9.8,1,9,1),
                c5=c(3,8,1,7,3,5),
                c6=c(2,3,5,2,5,7),
                row.names = c("r1","r2","r3","r4","r5","r6"))

output:

        c1    c2     c3  c4 c5 c6
r1   1.000 5.234  7.000 4.0  3  2
r2   2.000 5.000  6.000 1.0  8  3
r3   3.000 6.000  8.000 9.8  1  5
r4   8.000 3.000  4.300 1.0  7  2
r5   1.000 3.100  2.000 9.0  3  5
r6 300.234 4.233 60.191 1.0  5  7

After the round function output should be:

        c1    c2     c3  c4 c5 c6
r1   1.000 5.234  7.000 4.0  3  2
r2   2.000 5.000  6.000 1.0  8  3
r3   3.000 6.000  8.000 9.8  1  5
r4   8.000 3.000  4.300 1.0  7  2
r5   1.000 3.100  2.000 9.0  3  5
r6   300.23 4.233  60.19  1.0  5  7

Upvotes: 1

Views: 311

Answers (1)

myincas
myincas

Reputation: 1530

try this sapply(x, function(y) ifelse(y > 60, round(y, 2), y))

Upvotes: 4

Related Questions