r语言 - 如何将过滤行中的值(基于给定值)乘以同一行中的另一个值



我需要将"收入"栏中的每个值相乘;按列中每一行的值"Imps"除以1000,但只针对ID 2324。那么新的价值应该取代原来的价值(收入)。当ID不同时,"revenue"列中的值应保持不变。

ID Revenue Imps
1 8754  124.58 5429
2 8754   23.24 2393
3 8754  490.37 8845
4 2324   13.44 8934
5 2324   88.93 2345
6 1293   92.61 4985
7 1293   18.44 4592

我想补充的是,上面的表只是大表的一部分,它每天调整行数。

提前感谢您的帮助!

这是我尝试过的:

Revenue <- ifelse(ID == "2324", Revenue %*% Imps / 1000, Revenue)

但我认为它乘以"Imps"列中的值的总和。因为最终值比预期的大得多。

数据示例:

structure(list(ID = c(8754, 8754, 8754, 2324, 2324, 1293, 1293
), Revenue = c(124.58, 23.24, 490.37, 13.44, 88.93, 92.61, 18.44
), Imps = c(5429, 2393, 8845, 8934, 2345, 4985, 4592)), class = "data.frame", row.names = c(NA, 
-7L))

这解决你的问题了吗?

df <- structure(list(ID = c(8754, 8754, 8754, 2324, 2324, 1293, 1293
), Revenue = c(124.58, 23.24, 490.37, 13.44, 88.93, 92.61, 18.44
), Imps = c(5429, 2393, 8845, 8934, 2345, 4985, 4592)),
class = "data.frame", row.names = c(NA, -7L))
df
#>     ID Revenue Imps
#> 1 8754  124.58 5429
#> 2 8754   23.24 2393
#> 3 8754  490.37 8845
#> 4 2324   13.44 8934
#> 5 2324   88.93 2345
#> 6 1293   92.61 4985
#> 7 1293   18.44 4592
df$Revenue <- ifelse(df$ID == "2324", df$Revenue * (df$Imps / 1000), df$Revenue)
df
#>     ID  Revenue Imps
#> 1 8754 124.5800 5429
#> 2 8754  23.2400 2393
#> 3 8754 490.3700 8845
#> 4 2324 120.0730 8934
#> 5 2324 208.5409 2345
#> 6 1293  92.6100 4985
#> 7 1293  18.4400 4592

由reprex包(v2.0.1)在2022-11-10创建

最新更新