Laura Grob
Laura Grob

Reputation: 31

R how to conditionally update a numeric value in a data frame

I am trying to update a value in a data frame that is numeric when it is above a certain value due to input error. The value should be in the hundreds but, on occasion is in the thousands as it has an extra zero. Data Frame is called df and the column is called Value1

Value1 (sample values)
650
6640
550

The value for 7650 should be 765. I am trying to use the following:

df$Value1[df$Value1>1000] <- df$Value1/10

This is generating very odd results. I end up not having values greater than 1000 but, a value of 6640 became 74.1 instead of 664 as I expected.

Any suggestions?

Thanks in advance

Upvotes: 3

Views: 321

Answers (3)

akrun
akrun

Reputation: 887213

Or we can use data.table (data from @bgoldst's post)

library(data.table)
setDT(df)[Value1 > 1000, Value1 := Value1/10]
df
#   Value1
#1:    650
#2:    664
#3:    550

Upvotes: 1

bgoldst
bgoldst

Reputation: 35314

Here's how to do this in one line, without having to compute the target row indexes twice:

df$Value1[ris <- which(df$Value1>1000)] <- df$Value1[ris]/10;
df;
##   Value1
## 1    650
## 2    664
## 3    550

Data

df <- data.frame(Value1=c(650L,6640L,550L));

Upvotes: 2

Ram K
Ram K

Reputation: 1785

Here is one way :

 #Sample data frame
 d1
  Value1
1    650
2   6640
3    550

d1$Value1 = as.numeric(substr(d1$Value1,1,3))

#result
d1
  Value1
1    650
2    664
3    550

Upvotes: 0

Related Questions