循环并减去R中的两列

时间:2018-01-29 14:23:16

标签: r loops

我的df看起来像这样:

 Year Subscribers Forecast AbsError
1 2006    23188171        0        0
2 2007    28745769        0        0
3 2008    34880964        0        0
4 2009    46373266        0        0

我有一个填充预测列的lop,然后它应该从预测值中减去用户值并将该数字放入AbsError列,如下所示:

 Year   Subscribers    Forecast     AbsError
1 2006    23188171     9680000       13508171
2 2007    28745769     27960000      46240000
3 2008    3488096      46240000      11359036

My Loop看起来像这样: for (i in 1:nrow(new.phone)) { new.phone$Forecast[i] <- ((1.828e+07 )*new.phone$Year[i]) + (-3.666e+10) new.phone$AbsError <- abs((new.phone$Subscribers[i] - new.phone$Forecast[i])) }

虽然这个循环给出了正确的预测值,但它给出了不正确的AbsError值,但我无法弄清楚原因。所有AbsError值都是10464033,但这是错误的。任何想法为什么会这样?

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

你不需要for循环来做到这一点。这可以满足您的需求:

repo link

答案 1 :(得分:2)

你刚刚错过了循环第二行的索引。应该是:new.phone$AbsError[i] <- [...]而不是new.phone$AbsError <- [...]

无论如何,你可以跳过你想要的循环:

new.phone$Forecast <- (1.828e+07) * new.phone$Year + (-3.666e+10) 
new.phone$AbsError  <- abs(new.phone$Subscribers - new.phone$Forecast)

new.phone
  Year Subscribers Forecast AbsError
1 2006    23188171  9680000 13508171
2 2007    28745769 27960000   785769
3 2008    34880964 46240000 11359036
4 2009    46373266 64520000 18146734

答案 2 :(得分:1)

在dplyr中尝试:

require(dplyr)

k <- read.table(text = "Year Subscribers Forecast AbsError
1 2006    23188171        0        0
2 2007    28745769        0        0
3 2008    34880964        0        0
4 2009    46373266        0        0")

k%>%mutate(Forecast = ((1.828e+07 )*Year) + (-3.666e+10) )%>%
  mutate(AbsError = abs(Subscribers-Forecast))

结果:

Year Subscribers Forecast AbsError
1 2006    23188171  9680000 13508171
2 2007    28745769 27960000   785769
3 2008    34880964 46240000 11359036
4 2009    46373266 64520000 18146734