Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Created August 28, 2024 04:34
Show Gist options
  • Save nilforooshan/134c1522b08413809e5ea0367c7bae43 to your computer and use it in GitHub Desktop.
Save nilforooshan/134c1522b08413809e5ea0367c7bae43 to your computer and use it in GitHub Desktop.
R: Replace NA with 0 in a range of columns

Replace NA with 0 in a range of columns

In this example, NA is replaced with 0 in the last two columns.

ped
#   id sire dam
# 1  1    6  11
# 2  2   NA  12
# 3  3    8  NA
# 4  4    9  NA
# 5  5   NA  15
ped[,(ncol(ped)-1):ncol(ped)] <- replace(ped[,(ncol(ped)-1):ncol(ped)], is.na(ped[,(ncol(ped)-1):ncol(ped)]), 0)
ped
  id sire dam
1  1    6  11
2  2    0  12
3  3    8   0
4  4    9   0
5  5    0  15
ped[ped == 0] <- NA
ped[,(ncol(ped)-1):ncol(ped)] <- lapply(ped[,(ncol(ped)-1):ncol(ped)], function(x) replace(x, is.na(x), 0))
ped
  id sire dam
1  1    6  11
2  2    0  12
3  3    8   0
4  4    9   0
5  5    0  15

For a data.table:

ped[ped == 0] <- NA
setDT(ped)
ped[,(ncol(ped)-1):ncol(ped) := lapply(.SD, function(x) replace(x, is.na(x), 0)), .SDcols = (ncol(ped)-1):ncol(ped)]
ped
      id  sire   dam
   <int> <num> <num>
1:     1     6    11
2:     2     0    12
3:     3     8     0
4:     4     9     0
5:     5     0    15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment