Englishman Bob
Englishman Bob

Reputation: 483

Create Multiple Missing Data Points in R

I wish to create multiple missing data points in R.

We'll start with my test data set:

v <- 1:25
matmiss <- matrix(v, nrow = 5)
dfmiss <- as.data.frame(matmiss)

(Yes there is an easier way to do this, but right now I don't care).

For my missing data my code looks like this:

dfmiss[1,1] <- NA
dfmiss[2,2] <- NA
dfmiss[3,3] <- NA
dfmiss[4,4] <- NA
dfmiss[5,5] <- NA

There has to be an easier way to do this, right? Additionally, I need a Swiss cheese solution -- how do I randomly make missing data?

Background: My interest is bettering my detection and interpolation of missing data.

Upvotes: 0

Views: 59

Answers (3)

rjen
rjen

Reputation: 1972

A tidyverse option.

library(dplyr)
library(tidyr)

dfmiss %>%
  mutate(id = row_number()) %>%
  pivot_longer(-id) %>%
  mutate(value = if_else(str_sub(name, -1) == id, NA_integer_, value)) %>%
  pivot_wider(names_from = name, values_from = value) %>%
  select(-id)

# # A tibble: 5 x 5
#      V1    V2    V3    V4    V5
#   <int> <int> <int> <int> <int>
# 1    NA     6    11    16    21
# 2     2    NA    12    17    22
# 3     3     8    NA    18    23
# 4     4     9    14    NA    24
# 5     5    10    15    20    NA


dfmiss %>%
  mutate(across(everything(), ~ sample(c(., NA), length(.))))

#   V1 V2 V3 V4 V5
# 1  5  7 11 17 21
# 2  4 10 NA 19 24
# 3  1  9 15 16 22
# 4 NA  8 12 18 NA
# 5  2 NA 14 NA 25

Upvotes: 1

Brian Davis
Brian Davis

Reputation: 992

Much easier to accomplish if you leave in matrix format.

matmiss[diag(matmiss)] <- NA
matmiss
     [,1] [,2] [,3] [,4] [,5]
[1,]   NA    6   11   16   21
[2,]    2   NA   12   17   22
[3,]    3    8   NA   18   23
[4,]    4    9   14   NA   24
[5,]    5   10   15   20   NA

matmiss <- matrix(v, nrow = 5)
N <- 5
matmiss[sample(v,N)] <- NA # "swiss cheese"
matmiss
     [,1] [,2] [,3] [,4] [,5]
[1,]   NA    6   11   16   21
[2,]   NA   NA   12   NA   22
[3,]    3    8   13   18   23
[4,]    4    9   14   19   24
[5,]    5   10   15   NA   25

Upvotes: 2

Taufi
Taufi

Reputation: 1577

Surprisingly the first time I ever used <<-

Data

v <- 1:25
matmiss <- matrix(v, nrow = 5)
dfmiss <- as.data.frame(matmiss)

NoN <- round(nrow(dfmiss)*ncol(dfmiss)/5)

Code

replicate(NoN, dfmiss[sample(nrow(dfmiss), 1), sample(nrow(dfmiss), 1)] <<- NA)

Output

  V1 V2 V3 V4 V5
1  1  6 11 16 21
2  2  7 NA 17 22
3  3  8 NA 18 23
4  4  9 14 19 24
5  5 NA NA NA 25

Upvotes: 1

Related Questions