How to omit missing values and move the values to places to complete the data frame structure in R?


When we have alternative missing values in two columns that makes the data frame look filled with values at alternate places in columns as well. In this case, we might want to remove those missing values so that the data frame becomes complete without any missing value. For this purpose we can use na.omit function with transform function as shown in the below examples.

Example

Consider the below data frame −

 Live Demo

x1<-rep(c(NA,5),times=10)
x2<-rep(c(1,NA),times=10)
df1<-data.frame(x1,x2)
df1

Output

 x1 x2
1 NA 1
2  5 NA
3 NA 1
4  5 NA
5 NA 1
6  5 NA
7 NA 1
8  5 NA
9 NA 1
10 5 NA
11 NA 1
12 5 NA
13 NA 1
14 5 NA
15 NA 1
16 5 NA
17 NA 1
18 5 NA
19 NA 1
20 5 NA

Replacing NA’s in both the columns using single line of code −

Example

df1<-na.omit(transform(df1,x2=c(NA,x2[-nrow(df1)])))
df1

Output

  x1 x2
2  5 1
4  5 1
6  5 1
8  5 1
10 5 1
12 5 1
14 5 1
16 5 1
18 5 1
20 5 1

Let’s have a look at another example −

Example

 Live Demo

y1<-rep(c(15,NA,25,NA),times=5)
y2<-rep(c(NA,414,NA,425),times=5)
df2<-data.frame(y1,y2)
df2

Output

  y1 y2
1  15 NA
2  NA 414
3  25 NA
4  NA 425
5  15 NA
6  NA 414
7  25 NA
8  NA 425
9  15 NA
10 NA 414
11 25 NA
12 NA 425
13 15 NA
14 NA 414
15 25 NA
16 NA 425
17 15 NA
18 NA 414
19 25 NA
20 NA 425

Replacing NA’s in both the columns using single line of code −

Example

df2<-na.omit(transform(df2,y2=c(NA,y2[-nrow(df2)])))
df2

Output

  y1 y2
3  25 414
5  15 425
7  25 414
9  15 425
11 25 414
13 15 425
15 25 414
17 15 425
19 25 414

Updated on: 17-Oct-2020

69 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements