I created a data frame with random values
n <- 50
df <- data.frame(id = seq (1:n),
age = sample(c(20:90), n, rep = TRUE),
sex = sample(c("m", "f"), n, rep = TRUE, prob = c(0.55, 0.45))
)
and would like to introduce a few NA
values to simulate real world data. I am trying to use apply
but cannot get there. The line
apply(subset(df,select=-id), 2, function(x) {x[sample(c(1:n),floor(n/10))]})
will retrieve random values alright, but
apply(subset(df,select=-id), 2, function(x) {x[sample(c(1:n),floor(n/10))]<-NA})
will not set them to NA
. Have tried with
and within
, too.
Brute force works:
for (i in (1:floor(n/10))) {
df[sample(c(1:n), 1), sample(c(2:ncol(df)), 1)] <- NA
}
But I'd prefer to use the apply
family.
Simply pass your dataframe into the following function. The only arguments are the frame you want to add NAs to and the number of features (columns) you want to have with NAs.
For example, using the full dataset from banking dataset from UCI:
And viewing the original missing data:
We can see there is no missing data in the original frame.
Now applying our function:
I think you need to return the
x
value from the function:but you also need to assign this back to the relevant subset of the data frame (and
subset(...) <- ...
doesn't work)(if you have only a single non-ID column you'll need
df[,!idCol,drop=FALSE]
)Return
x
within your function:Apply returns an array, thereby converting all columns to the same type. You could use this instead:
Or use a
for
loop:here is another simple way to go at it
your data frame
Number of missing required
sample row and column indices
remove duplication
use matrix indexing