Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对列求和并除以r中行中的非零值数_R_Sum_Aggregate - Fatal编程技术网

对列求和并除以r中行中的非零值数

对列求和并除以r中行中的非零值数,r,sum,aggregate,R,Sum,Aggregate,我希望聚合(求和)列,然后将聚合除以每行中非零值的数量。 样本数据: col 1 col 2 col 3 0 0 0 0 0 0 0.5 0.5 0 0 0.25 0 0.583 0.583 0.583 预期输出: sum 0 0 0.5 0.25 0.58

我希望聚合(求和)列,然后将聚合除以每行中非零值的数量。
样本数据

col 1    col 2    col 3          

    0         0        0
    0         0        0
    0.5       0.5      0 
    0         0.25     0
    0.583     0.583    0.583 
预期输出:

sum

    0
    0
    0.5
    0.25
    0.583
感谢您提供有关如何在r中执行此操作的任何提示 干杯

df <- read.table(text="0         0        0
                       0         0        0
                       0.5       0.5      0 
                       0         0.25     0
                       0.583     0.583    0.583")

df2 <- data.frame(results=apply(df,1,function(x){
ifelse(any(x!=0),sum(x)/length(x[x!=0]),0)}))
df2
 results
1   0.000
2   0.000
3   0.500
4   0.250
5   0.583