1

I have a data table which includes NAs in some cells as below. Datatable:

enter image description here However, I want to repeat 1st row in the column called "Category" to the following two rows written "NA" without any change in other columns which are "Numeric" and "Numeric.null". Same thing for 4th row in Category, repeat it to 5th and 6th rows but no change in other columns. New:

2

I'm just learning R programming. I have tried rep function. But I couldn't do. Please help me.

arg0naut91
  • 14,574
  • 2
  • 17
  • 38
econes
  • 33
  • 3
  • 1
    Does this answer your question? [Replacing NAs with latest non-NA value](https://stackoverflow.com/questions/7735647/replacing-nas-with-latest-non-na-value) – arg0naut91 Mar 31 '20 at 20:36

1 Answers1

1

We can use fill from tidyr

library(dplyr)
library(tidyr)
df1 <- df1 %>% 
          fill(Category)
df1
#  Category Numeric Numeric.null
#1        A       1            1
#2        A       2            2
#3        A       3            4
#4        D       4            7
#5        D       5            6
#6        D       6            8
#7        E       7           11

Or using data.table with na.locf0

library(data.table)
library(zoo)
setDT(df1)[, Category := na.locf0(Category)][]

data

df1 <- structure(list(Category = c("A", NA, NA, "D", NA, NA, "E"), Numeric = 1:7, 
    Numeric.null = c(1L, 2L, 4L, 7L, 6L, 8L, 11L)), 
    class = "data.frame", row.names = c(NA, 
-7L))
akrun
  • 874,273
  • 37
  • 540
  • 662