sasalean.blogg.se

Simple for loop in r
Simple for loop in r













simple for loop in r

So can you see why we used ncol(city) - 1 when we first set up our loop? As we have four columns in our city data frame if we didn’t use ncol(city) - 1 then eventually we’d try to add the 4 th column with the non-existent 5 th column.Īgain, it’s a good idea to test that we are getting something sensible from our loop (remember, check, check and check again!). The multiply_columns() function multiplies the city ( nairobi) and city ( genoa) columns and stores it in the temp] which is the third element of the temp list. The third and final iteration of the loop i takes on the value 3. The multiply_columns() function multiplies the city ( aberdeen) and city ( nairobi) columns and stores it in the temp] which is the second element of the temp list. The second iteration of the loop i takes on the value 2. The multiply_columns() function multiplies the city ( porto) and city ( aberdeen) columns and stores it in the temp] which is the first element of the temp list. So in the first iteration of the loop i takes on the value 1. We’ll come back to why we need to subtract 1 from this in a minute.

simple for loop in r

The ncol() function returns the number of columns in our city data frame which is 4 and so our loop runs from i = 1 to i = 4 - 1 which is i = 3.

simple for loop in r

When we specify our for loop notice how we subtracted 1 from ncol(city). Temp <- list() for (i in 1 :( ncol(city) - 1)) # Warning in multiply_columns(x = city, y = city): The function has # produced NAs # Warning in multiply_columns(x = city, y = city): The function has # produced NAs 1.4.2 Integrated developement environements.















Simple for loop in r