CsabaD - 9 days ago 5

R Question

I have a df like this:

`> df`

symbol x1 x2

1 A 3.6 5.2

2 A 10.0 4.8

3 A 5.2 0.2

4 A -10.2 0.4

5 A 5.4 -2.5

6 B 9.9 6.5

7 B 15.8 -1.8

8 B 4.5 -5.9

9 C -2.0 0.5

10 C -10.0 2.6

11 C 7.7 8.9

12 C 10.5 18.5

I want to calculate the r squared between x1 and x2 column by symbol so I want to get a new df like this

`symbol r squared`

1 A 0.27

2 B 0.30

3 C 0.68

I use ifelse but it isn't working.

`for (i in 1:12){`

results[i] <- ifelse(df$symbol == symbollist[i], summary(lm(df$x1~df$x2))$r.squared,0)

}

How can I solve this problem in R?

Answer

You can use `by`

to perform `lm`

for each symbol:

```
by(df, df$symbol, function(x) summary(lm(x1~x2, x))$r.squared)
df$symbol: A
[1] 0.07445258
-----------------------------------------------------------------------------------------------------------
df$symbol: B
[1] 0.09014209
-----------------------------------------------------------------------------------------------------------
df$symbol: C
[1] 0.687236
```

Source (Stackoverflow)

Comments