简体   繁体   中英

How to fill the empty cells in data.frame in R

I am working on a data.frame in R and want to fill the empty cells in a specific way. In below table, the header is 'Dismissal' and there are two empty cells in second and fourth row. Since there are more than 100,000 rows, in real data.frame, I want to fill those empty cells at once in a way that fill the second row as NIL and the fourth row as D. To say again, filling the empty cells according to the value of the very former existing cell.

    Dismissal      |
--------------------
        NIL        |
--------------------
    (empty)        |  
--------------------
         D         |
--------------------
     (empty)       |

You can just loop through the data frame as follows

for (i in 1:nrow(df)){
         if(df$Dismissal[i]=="empty")({ 
         df$Dismissal[i]=df$Dismissal[i-1] 
         }
    }

if the field has an NA value, because of the empty cell in your csv import, you will need to change the loop a bit:

for (i in 1:nrow(df)){
         if (is.na(df$Dismissal[i])){
         df$Dismissal[i]=df$Dismissal[i-1] 
         }
    }

NA values to not work in ==, != or >=, <= so you need to ask is.na() or !is.na() instead.

A non-looping solution using dplyr and zoo :

library(dplyr)
library(zoo)
test.dat <- data.frame('Dismissal' = c('N', NA, 'D', NA, NA, 'C', NA))
test.dat$Dismissal <- as.character(test.dat$Dismissal)

test.dat %>%
  mutate(Test = ifelse(is.na(Dismissal),
                       #use fill forward function from zoo package
                       zoo::na.locf(lag(Dismissal), na.rm = F),
                       Dismissal))

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