简体   繁体   English

如何在R中的data.frame中填充空白单元格

[英]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. 我正在R中的data.frame上工作,并希望以特定的方式填充空白单元格。 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. 由于在实际data.frame中有超过100,000行,我想一次填充这些空单元格,将第二行填充为NIL,将第四行填充为D。再说一遍,根据以前存在的单元格的值。

    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: 如果该字段具有NA值,则由于csv导入中的单元格为空,您将需要对循环进行一些更改:

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. NA值不适用于==, != or >=, <=因此您需要询问is.na()!is.na()

A non-looping solution using dplyr and zoo : 使用dplyrzoo非循环解决方案:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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