How to calculate variance in R for a certain number of observations (not a whole column)?

Viewed 40

I have a data frame, and I'm trying to calculate the variances (of a column variable) for the first 95 observations and the last 95 observations. Is there a way of doing this simply? I'm new to R...

1 Answers

Suppose all columns of your data.frame df are numeric, you can use

sapply(head(df, 95), var)
sapply(tail(df, 95), var)

If only some columns are numeric, compute variance for those numeric ones:

j <- sapply(df, is.numeric)
sapply(head(df[j], 95), var)
sapply(tail(df[j], 95), var)
Related