LLL
LLL

Reputation: 743

conditional arithmetic operation error message

In my data frame, I'd like to calculate the cost of a product (hat, shoe or umbrella) by multiplying the DiscVar variable with a number (1400, (1400-342), or (1400+500)) depending on the product.

The problems that the calculations only work out for the first operation, ie dfq$DiscVar * 1400, and I have no idea why.

Thanks for any help!!

# Data & arithmetic operation  
dfq <- data.frame(ObjVar=c("hat","hat","shoe","shoe","umbrella"),DiscVar=c(0.19,0.39,0.18,1.00,0.64))
dfq$CostVar[dfq$ObjVar == "hat"] <- dfq$DiscVar * 1400
dfq$CostVar[dfq$ObjVar == "shoe"] <- dfq$DiscVar * (1400-342)
dfq$CostVar[dfq$ObjVar == "umbrella"] <- dfq$DiscVar * (1400+500)

Upvotes: 0

Views: 23

Answers (2)

akrun
akrun

Reputation: 887691

If there are many unique elements, we can create a named vector to match the elements in 'ObjVar', and then do the arithmetic

nm1 <- setNames(c(1400, 1400-342, 1400 + 500), c('hat', 'shoe', 'umbrella'))
dfq$CostVar <- with(dfq, nm1[ObjVar] * DiscVar)

Upvotes: 0

Rui Barradas
Rui Barradas

Reputation: 76621

You subset the results but forget to subset the operand.

dfq <- data.frame(ObjVar=c("hat","hat","shoe","shoe","umbrella"),DiscVar=c(0.19,0.39,0.18,1.00,0.64))

dfq$CostVar <- 0    # First, create the entire new column
dfq$CostVar[dfq$ObjVar == "hat"] <- dfq$DiscVar[dfq$ObjVar == "hat"] * 1400
dfq$CostVar[dfq$ObjVar == "shoe"] <- dfq$DiscVar[dfq$ObjVar == "shoe"] * (1400-342)
dfq$CostVar[dfq$ObjVar == "umbrella"] <- dfq$DiscVar[dfq$ObjVar == "umbrella"] * (1400+500)

Upvotes: 2

Related Questions