简体   繁体   中英

Loop through and subtract two columns in R

I have a df that looks like this:

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

I have a lop that fills in the forecast column and then it should subtract the subscriber value from the forecast value and put that number into the AbsError column, like so:

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

My Loop looks like this: 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])) }

Although this loop is giving the correct forecasted values, its giving the incorrect AbsError values, but i cannot figure out why. All the AbsError values are 10464033, but that is wrong. Any ideas why this is?

Thanks for the help!

You don't need a for loop to do that. This does what you need:

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

You were just missing the index in the second line of the loop. Should be: new.phone$AbsError[i] <- [...] not new.phone$AbsError <- [...] .

Anyway, you could skip the loop of you want:

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

Try this in 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))

Results:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM