Reputation: 341
i have a data set :
X Y
20 12
24 11
12 7
10 2
41 24
13 9
50 17
4 12
17 12
35 19
Now i have to find the mean of Y when 20 < X < 50.
My attempt:
data <- data.frame(X=c(20,24,12,10,41,13,50,4,17,35),
Y=c(12,11,7,2,24,9,17,12,12,19))
sub <- subset(data,X>20 & X<50)
mean(sub$Y)
Is there any direct way to find the mean of Y when 20< X<50 without modifying the original data frame ,ie, without subset it?
Upvotes: 0
Views: 153
Reputation: 121578
Or, using data.table
for its syntactic sugar:
library(data.table)
DT <- data.table(data)
DT[X>20 & X <50,mean(Y)]
[1] 18
Upvotes: 4
Reputation: 6535
Not sure what you mean by "without subset it". At some point you are going to have to subset the data in some way since you are looking for the mean of a subset of the data. If you mean "don't call the subset function and save another copy of the data" you can just do
mean(data$Y[data$X > 20 & data$X < 50])
# [1] 18
Upvotes: 7