torakxkz
torakxkz

Reputation: 493

Calculate mean value of the same column depending on each all other columns

Suppose that I have the following df

df <- structure(list(var1 = c(1, 0, 1, 0, 0 , 1 ), var2 = c(0, 
0, 0, 1, 1, 0), var99 = c(0, 1, 1, 1, 1, 0), value = c(154, 
120, 100, 180, 200, 460)), .Names = c("var1", "var2", "var99", "value" ), row.names = c(NA, -6L), class = "data.frame")

And I want to achieve this output data:

structure(list(var = c("var1", "var2", "var99"), mean = c(238, 
190, 150)), .Names = c("var", "mean"), row.names = c(NA, -3L), class = 
"data.frame")

This is: to obtain the mean value of column 'value' for every other column: var1, var2, ..., var99. Only rows with 1's will be taken into account to compute the mean.

I have done it with a for loop:

l <- vector("list", 3)
for (i in 1:3)
l[[i]] <- mean(df$value[df[,i]==1], na.rm = T)
i <- i+1

Can anyone suggest me another approach omitting the loop with Base R when possible?

Upvotes: 1

Views: 94

Answers (2)

r.user.05apr
r.user.05apr

Reputation: 5456

Or:

sapply(subset(df, select = -value), function(x) mean(df$value[x == 1]))

Upvotes: 1

AdamO
AdamO

Reputation: 4920

sapply(df[, -4], weighted.mean, x=df[, 4])

Or

colSums(sweep(df[, -4], 1, df[, 4], `*`)) / colSums(df[, -4])

Upvotes: 2

Related Questions