How can I calculate the row-wise lm() / coeffs of multiple variables in an df, which are stored in columns?
I have this kind of data (just examples):
set.seed(1)
foo <- data.frame(trialNumber= 1:10,
Nr1 = runif(10),
Nr2 = runif(10),
Nr3 = runif(10),
Nr4 = runif(10),
Nr5 = runif(10),
Nr6 = runif(10),
slope = NA)
The trialNumber represents each one of a trial where I measured six values directly behind each other.
I managed to plot these data with a linear regression line with boxplots using this code:
foo_1 <- reshape2::melt(data = foo, id.vars = "trialNumber", measure.vars = c("Nr1", "Nr2", "Nr3", "Nr4", "Nr5", "Nr6"))
p <- ggplot(data = foo_1) +
aes(x = variable,
y = value) +
geom_boxplot() +
geom_jitter(shape = 1, position = position_jitter(0.1)) +
ylim(0, NA) +
geom_smooth(method = "lm", se = TRUE, formula = y ~ x, aes(group = 1))
print(p)
which results in this diagram:
Now this is the linear regression line of all the trials, but I want the slope (or regression coefficients) row-wise stored in the variable "slope".
In the end I want a df like this:
trialnumber | Nr1 | Nr2 | Nr3 | Nr4 | Nr5 | Nr6 | slope
1 | 0.26550866 | 0.2059746|0.93470523|0.4820801|0.8209463|0.47761962|e.g. 0.07
2 | ? | ? | ? | ? | ? | ? |e.g. 3.81
.
.
.
How can I achieve this? I already looked into the apply function, but I could not figure out how to use this.
Thank you very much in advance!
