I have (what I think should be) a straight forward problem in R, and can't seem to get it to work. Hope you can help.
I have a data frame e.g.:
x y z
1 2 a
2 3 a
3 4 a
4 5 b
5 6 b
6 7 b etc...
And I'm fitting a linear model (y ~ x) for each z value subset (e.g. a, b...) and extracting the gradient.
It works when I select 'a' using a with statement as such:
coef(with(subset(data.frame, z == "a"), {lm(y ~ x)
}))[2]
But my problem is that I have more than 1000 unique values in the Z column. So I tried to set up a loop (I know R users hate loops!) to do this for each value of z in turn and return the result in a data frame. Code is:
gradient.lm = NULL
unique.z <- as.matrix((unique(data.frame$z)))
count.z <- nrow(unique.z)
for (i in 1:count.z) {
gradient.lm[i] = coef((with(subset(data.frame, z == [i]), {lm(y ~ z)
})))[2]
}
But this is not working, and giving me the error code:
> for (i in 1:count.z) {
+ activity.lm[i] = coef((with(subset(data.frame, z == [i]), {lm(y ~ x)
Error: unexpected '[' in:
"for (i in 1:count.z) {
activity.lm[i] = coef((with(subset(data.frame, z == ["
> })))[2]
Error: unexpected '}' in " }"
> }
Error: unexpected '}' in "}"
My guess was that it doesn't realise that there is an [i] within the with function.
I can't find a way of making this work, or think of another way of doing it. If you have any suggestions they would be hugely appreciated.
z == unique.z[i]instead ofz == [i]data.frame))