Home > Software design >  How to replace NA values in one column of a data frame, with values from a column in a different dat
How to replace NA values in one column of a data frame, with values from a column in a different dat

Time:06-27

How do I replace the NA values in 'example' with the corresponding values in 'example 2'? So 7 would take the place of the first NA and 8 would take the place of the second NA etc. My data is much larger so I would not be able to rename the values individually for the multiple NAs. Thanks

example <- data.frame('count' = c(1,3,4,NA,8,NA,9,0,NA,NA,7,5,8,NA))
    
example2 <- data.frame('count' = c(7,8,4,6,7))

CodePudding user response:

Another possible solution, based on replace:

example$count <- replace(example$count, is.na(example$count), example2$count)
example

#>    count
#> 1      1
#> 2      3
#> 3      4
#> 4      7
#> 5      8
#> 6      8
#> 7      9
#> 8      0
#> 9      4
#> 10     6
#> 11     7
#> 12     5
#> 13     8
#> 14     7

CodePudding user response:

You can try with :

example[is.na(example),] <- example2 

Which will give you :

count
1      1
2      3
3      4
4      7
5      8
6      8
7      9
8      0
9      4
10     6
11     7
12     5
13     8
14     7

EDIT: Since you probably have more than just one column in your dataframes, you should use :

example$count[is.na(example$count)] <- example2$count

CodePudding user response:

Another option using which to check the index of NA values:

ind <- which(is.na(example$count))
example[ind, "count"] <- example2$count

Output:

   count
1      1
2      3
3      4
4      7
5      8
6      8
7      9
8      0
9      4
10     6
11     7
12     5
13     8
14     7
  •  Tags:  
  • r
  • Related