I'm performing permutations and running apply to plot abline
or lines from a linear model. But when using apply, I get "NULL" (but it draws the lines). How do I make the "NULL" go away and why is it doing that?
set.seed(12345678)
n = 100; beta0 = 2.5; beta1 = 0.8
x.lm = rnorm(n = n, mean = 10, sd = 1)
err = rnorm(n = n, mean = 0, sd = 1)
# Linear combination
y.lm = beta0 beta1*x.lm err
# Make a dataframe of the data
df.lm = data.frame(x = x.lm, y = y.lm)
par(mar = c(4,4,.5,.5))
# Colour
b.5 = scales::alpha("black",alpha = .5)
# PLot the data
plot(y~x, data = df.lm, pch = 19, col = b.5)
# Add permutations
permutate.df =replicate(n = 200, # nperm
expr = data.frame(y = sample(df.lm$y,size = nrow(df.lm), replace = FALSE), x = df.lm$x),
simplify = FALSE)
lm.out.perm = mapply(lm, permutate.df)
apply(lm.out.perm,2,function(x) abline(x,col = scales::alpha("orange",.5)))
CodePudding user response:
abline
return NULL, usually invisibly. Suggest writing the part from plot
onwards like this. Alternately use invisible(Map(...))
in the last line. No packages are used.
plot(y~x, data = df.lm, pch = 19, col = adjustcolor("black", alpha = 0.5))
permuted_dfs <- with(df.lm, replicate(n = 200,
expr = data.frame(y = sample(y, replace = FALSE), x),
simplify = FALSE))
fms <- Map(lm, permuted_dfs) # fitted models
junk <- Map(abline, fms, col = adjustcolor("orange", alpha = 0.5))
or as a pipeline if you don't need the intermediate results.
plot(y~x, data = df.lm, pch = 19, col = adjustcolor("black", alpha = 0.5))
df.lm |>
with(replicate(n = 200,
expr = data.frame(y = sample(y, replace = FALSE), x),
simplify = FALSE)) |>
Map(f = lm) |>
Map(f = abline, col = adjustcolor("orange", alpha = 0.5)) |>
invisible()