简体   繁体   中英

Looping through rows and columns in R does not work

I am just trying to fill gaps but in a loop. It is a monthly data, and fill_gaps produces NAs for every day. I am not sure why.

for (x in 2:length(differencing)){
  for(micky in 1:length(differencing$`d_ BA`)){
    if(is.na(differencing[micky,x])== T){
      differencing[micky,x] = differencing[micky-1,x]
    }
  }
}

here is the error that I am getting:

Error: Assigned data `differencing[(micky - 1), x]` must be compatible with row subscript `micky`.
x 1 row must be assigned.
x Assigned data has 0 rows.
i Row updates require a list value. Do you need `list()` or `as.list()`?
Run `rlang::last_error()` to see where the error occurred.

This can be easily done using fill

library(tidyr)
library(dplyr)
differencing %>%
    fill(everything())

Or we can use na.locf from zoo

library(zoo)
na.locf(differencing)

In the OP's loop, in the first line, it would be

for (x in  2:length(differencing$`d_ BA`)
   ...

as length of a data.frame will be the number of columns (as mentioned in the comments) and is different from length of a column ie vector


As the OP mentioned none of them works (OP didn't provide any example), using a small reproducible example ('tmp')

tmp %>%
   fill(everything())
#                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout 18.7   6  258 110 3.15 3.440 17.02  0  0    3    2
#Valiant           18.1   6  258 110 2.76 3.460 20.22  1  0    3    1

or using na.locf

na.locf(tmp)
#                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout 18.7   6  258 110 3.15 3.440 17.02  0  0    3    2
#Valiant           18.1   6  258 110 2.76 3.460 20.22  1  0    3    1

data

tmp <- head(mtcars)
tmp[c(2, 5, 6), c(3, 4, 2)] <- NA

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