[R] Adding NAs to data.frame
Gabor Grothendieck
ggrothendieck at gmail.com
Sun May 9 00:44:59 CEST 2010
That seems to be a suitable situation for a loop although you might
wish to write it like this:
for ( nm in names(df) ) df[ v[[nm]], nm ] <- NA
Note that R does not require semicolons at the end of each statement.
On Sat, May 8, 2010 at 11:12 AM, <soeren.vogel at eawag.ch> wrote:
> Hello, after the creation of a data.frame I like to add NAs as follows:
>
> n <- 743;
> x <- runif(n, 1, 7);
> Y <- runif(n, 1, 7);
> Ag6 <- runif(n, 1, 7);
> df <- data.frame(x, Y, Ag6);
> # a list with positions:
> v <- apply(df, 2, function(x) sample(n, sample(1:ceiling(5*n/100), 1), repl=F));
> # a loop too much?
> for (i in 1:length(df)){
> df[unlist(v[i]), i] <- NA;
> }
> summary(df);
>
> This works fine but it appears to me that there is a more elegant and simple way -- which one?
>
> Thanks
> Sören
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list