简体   繁体   中英

How to replace NA values in one column of a data frame, with values from a column in a different data frame?

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

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

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

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

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