Borexino
Borexino

Reputation: 842

Compute rowMeans across different columns in each row

I've a DF like this:

df <- read.table(text = "x1 x2 x3 x4 x5 x6 start end
                    1 2 2 1 2 3 2 6 
                    2 3 2  5  7  9 1 3 
                    1 9 12 6 1 1 3 6 ", header = TRUE)

start and endindicate the number of the columns that should be included in the rowMeans. i.e. First row: mean from x2 to x6; Second row: mean from x1 to x3 and so on

I tried this with no success:

df$means <- rowMeans(df[,df$X7:df$X8]) 

Upvotes: 1

Views: 179

Answers (1)

LyzandeR
LyzandeR

Reputation: 37889

One way with apply:

apply(df, 1, function(x) mean(as.numeric(x[x[7]:x[8]], na.rm = TRUE)))
#[1] 2.000000 2.333333 5.000000

A bit of a description. apply will iterate over each row. variable x represents each row. So, we are telling R to subset each row based on columns 7 and 8 and then calculate the mean.

Upvotes: 3

Related Questions