条件算术运算错误信息
conditional arithmetic operation error message
在我的数据框中,我想通过将 DiscVar
变量乘以一个数字(1400
、(1400-342)
,或 (1400+500)
),具体取决于产品。
只有第一次运算才算出来的问题,即dfq$DiscVar * 1400
,我也不知道为什么。
感谢您的帮助!!
# 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)
您对结果进行了子集化,但忘记了对操作数进行子集化。
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)
如果唯一元素比较多,我们可以创建一个命名的vector
来匹配'ObjVar'中的元素,然后做算术
nm1 <- setNames(c(1400, 1400-342, 1400 + 500), c('hat', 'shoe', 'umbrella'))
dfq$CostVar <- with(dfq, nm1[ObjVar] * DiscVar)
在我的数据框中,我想通过将 DiscVar
变量乘以一个数字(1400
、(1400-342)
,或 (1400+500)
),具体取决于产品。
只有第一次运算才算出来的问题,即dfq$DiscVar * 1400
,我也不知道为什么。
感谢您的帮助!!
# 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)
您对结果进行了子集化,但忘记了对操作数进行子集化。
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)
如果唯一元素比较多,我们可以创建一个命名的vector
来匹配'ObjVar'中的元素,然后做算术
nm1 <- setNames(c(1400, 1400-342, 1400 + 500), c('hat', 'shoe', 'umbrella'))
dfq$CostVar <- with(dfq, nm1[ObjVar] * DiscVar)