I'm still having problems calculating numbers.
Trying to find the amount of numbers inside [-0.5 , 0.5] the first line, and the amount of numbers outside the same range in the second line.
I use abc = rnorm(100, mean=0, sd=1). So I have 100 numbers in total, but i only have 35 numbers inside the range, and 35 outside the range, that dosen't add up to 100.
length(abc[abc>=-0.5 & abc<=0.5])
[1] 35
length(abc[abc<-0.5 & abc>0.5])
[1] 35
Then I tried:
length(which(abc>=-0.5 & abc<=0.5))
[1] 40
length(which(abc<-0.5 & abc>0.5))
[1] 26
And it still doesn't add up to 100. What's wrong?
You are after:
R> set.seed(1)
R> abc = rnorm(100, mean=0, sd=1)
R> length(abc[abc >= -0.5 & abc <= 0.5])
[1] 41
R> length(abc[abc < -0.5 | abc > 0.5])
[1] 59
What went wrong
Two things:
abc < -0.5 & abc > 0.5 is asking for values less than -0.5 and greater than 0.5However, you actually had: abc[abc<-0.5 & abc>0.5] This does something a bit different due to scoping. Let's pull it apart:
R> abc[abc<-0.5 & abc>0.5]
[1] 1.5953 0.7383 0.5758 1.5118 1.1249 0.9438 <snip>
Now let's look at abc
R> abc
[1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE
You've changed the value of abc! This is because <- is the assignment operator. You have set abc equal to 0.5 & abc > 0.5. To avoid this, use spacing (as in my code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With