Try to search your question here, if you can't find : Ask Any Question Now ?

How to get mean of nonzero elements by row, varying which columns are used by a condition

HomeCategory: stackoverflowHow to get mean of nonzero elements by row, varying which columns are used by a condition
gaurav asked 1 week ago

Suppose I have the following data table:

  tempmat=matrix(c(1,1,0,4,1,0,0,4,0,1,0,4, 0,0,1,4, 0,0,0,5),5,4,byrow=T)
  tempmat=rbind(rep(0,4),tempmat)
  tempmat=data.table(tempmat)
  names(tempmat)=paste0('prod1vint',1:4)

Which looks like:

       prod1vint1 prod1vint2 prod1vint3 prod1vint4
1:          0          0          0          0
2:          1          1          0          4
3:          1          0          0          4
4:          0          1          0          4
5:          0          0          1          4
6:          0          0          0          5

I want to define a new column, TN, that takes the mean row-wise in the following fashion.

  1. For each row, find the first nonzero element going left to right.
  2. Then, find the mean of all nonzero elements to the RIGHT of that.

The output should be:

   prod1vint1 prod1vint2 prod1vint3 prod1vint4   TN
1:          0          0          0          0   NA
2:          1          1          0          4   2.5
3:          1          0          0          4   4
4:          0          1          0          4   4
5:          0          0          1          4   4 
6:          0          0          0          5   NA

The NA’s arise because in 1: there are no nonzero elements, and in 6: there are no nonzero elements to the right of the first nonzero element.

1 Answers
Best Answer
Mannu answered 1 week ago
Your Answer

17 + 6 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com