0

I have two variables and I want to calculate the mean of the second variable into class according to the first.

The first variable is the time and take 100 values

The second variable is an index. I have divided the first variable into 4 classes (not equals). I want to calculate the mean of index for each class/group of time and then plot it according to the grouped time.

Important: I don’t want to use another package in R. Thanks in advance

time<-c(1:100)
index<-rnorm(100,0,1)
time_groups<-table(cut(time, seq(0,100,25)))

The cells of time are related with the cells of index.

How can I calculate the mean of index for each class?

The results should be:

group  index
0-25   mean index
25-50  mean index
50-75  mean index
75-100 mean index
George
  • 23
  • 4

2 Answers2

1
set.seed(1)
time <- 1:100
groups <- cut(time, breaks=c(0, 20, 50, 70, 100))
index <- rnorm(length(time))
barplot(tapply(index, groups, mean), xlab="Time group", ylab="Index mean")

enter image description here

lukeA
  • 53,097
  • 5
  • 97
  • 100
0

This is a possible answer, however is very slow for large samples...If you have a better answer, please help.

time<-c(1:100)
index<-rnorm(100,0,1)

h1<-seq(0,max(time)+25,25)
h2<-c(1:length(h1)-1)
group<-rep(NA,length(time))
for (j in 1:length(h1)){
for (i in 1:100){
if (h1[j]<=time[i] & h1[j+1]>time[i])
(group[i]<-h2[j])
}}
aggregate(index, by=list(group), mean)
George
  • 23
  • 4