Selrac
Selrac

Reputation: 2293

Round conditionally numbers in R

How can I round conditionally the values of a column in a dataframe in R? I need to round to the lower 10 from 0-89 and not from 90-100. For example:

ID    value
A     15
B     47
C     91
D     92

has to be changed to

ID    value
A     10
B     40
C     91
D     92

so, no changes for C/D and A/B rounded down

Any ideas?

Thanks

Upvotes: 0

Views: 1402

Answers (2)

etienne
etienne

Reputation: 3678

You can do it like this:

df$value[df$value < 90] <- floor(df$value[df$value < 90] / 10) * 10

# ID value
# 1  A    10
# 2  B    40
# 3  C    91
# 4  D    92

As a reminder, here is your data:

df <- structure(list(ID = c("A", "B", "C", "D"), value = c(15L, 47L, 
91L, 92L)), .Names = c("ID", "value"), class = "data.frame", row.names = c(NA, 
-4L))

Other solution using data.table:

library(data.table)
setDT(df)[, value:= as.numeric(value)][value<90, value:= floor(value/10) * 10]

# ID value
# 1:  A    10
# 2:  B    40
# 3:  C    91
# 4:  D    92

Upvotes: 1

989
989

Reputation: 12937

You could do:

df$value <- with(df, ifelse(value %in% c(0:89), value-(value%%10), value))

Upvotes: 1

Related Questions