R 在更改数据集中的值时遇到问题
我正在超市里对不同品牌的产品进行销售预测,我特别想用销售价格代替价格水平低于销售价格的DOVE除臭剂的正常价格。我在R中尝试了以下命令:R 在更改数据集中的值时遇到问题,r,R,我正在超市里对不同品牌的产品进行销售预测,我特别想用销售价格代替价格水平低于销售价格的DOVE除臭剂的正常价格。我在R中尝试了以下命令: newthesis$DOVERPrice[newthesis$DOVERPrice < newthesis$DOVEPrice] <- newthesis$DOVEPrice newthesis$DOVERPrice[newthesis$DOVERPrice
newthesis$DOVERPrice[newthesis$DOVERPrice < newthesis$DOVEPrice] <- newthesis$DOVEPrice
newthesis$DOVERPrice[newthesis$DOVERPrice
set.seed(1)
dtf <- as.data.frame(matrix(sample(1:20), 10))
dtf$max <- apply(dtf[,1:2], 1, max)
# or
dtf$max <- pmax(dtf[,1], dtf[,2])
head(dtf)
# V1 V2 max
# 1 6 3 6
# 2 8 2 8
# 3 11 20 20
# 4 16 10 16
试试。。。谢谢你的建议,我解决了这个问题:)
set.seed(1)
dtf <- as.data.frame(matrix(sample(1:20), 10))
dtf$max <- apply(dtf[,1:2], 1, max)
# or
dtf$max <- pmax(dtf[,1], dtf[,2])
head(dtf)
# V1 V2 max
# 1 6 3 6
# 2 8 2 8
# 3 11 20 20
# 4 16 10 16
dtf$V1[dtf$V1 < dtf$V2]
# is shorter than
dtf$V2
# this will work, because the two vectors are of the same length
dtf$V1[dtf$V1 < dtf$V2] <- dtf$V2[dtf$V1 < dtf$V2]
# that's why this works
dtf$V1[dtf$V1 < dtf$V2] <- NA
# and this
dtf$V1[dtf$V1 < dtf$V2] <- 1:2
# but not this
dtf$V1[dtf$V1 < dtf$V2] <- 1:3