2

I have a data frame, (aka df), and I want to multiply the Column Price when the column meets a specific condition, such as

df$US=='non US'`.

Here is my code:

df$Price <- df$Price[df$US=='non US']*0.85

Running the code above causes this error:

Error in `$<-.data.frame`(`*tip*`, CompPrice, value = c(140, 114.117647058824,  : 
  replacement has 142 rows, data has 400

I understand the reason the error occurs, however, I don't know how to modify just the rows that meet the condition.

Thanks in advance.

JΛYDΞV
  • 8,532
  • 3
  • 51
  • 77

2 Answers2

2

We need to specify the logical condition on the lhs of <- as the lhs includes the full 'Price' column

df$Price[df$US=='non US'] <- df$Price[df$US=='non US']*0.85

It is usually recommended to create an object before the assignment to avoid doing the same computation repeatedly

i1 <- df$US == 'non US'
df$Price[i1] <- df$Price[i1] * 0.85

With data.table, this syntax is more compact

library(data.table)
setDT(df)[US == 'non US', Price := Price * 0.85]
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You can use ifelse like so...

df$Price <- ifelse(df$US=='non US', df$Price * .85, df$Price)
Chuck P
  • 3,862
  • 3
  • 9
  • 20