Skip to content
Prev 14895 / 15379 Next

[R-es] Sumar positivos y negativos por separado

Hola,

Este sería un ejemplo reproducible rápido. A mí para esto me gusta rowise() de {dplyr}. En c_across() se pueden seleccionar las columnas a conveniencia. Seguramente haya una forma de evitar crear las funciones. Si la suma la quieres en valor absoluto multiplicas por -1 en suma_neg y listo.

Un saludo,
Emilio
+                 b = round(rnorm(10), 1),
+                 c = round(rnorm(10), 1))
a    b    c
1  -0.1  0.3 -0.4
2  -1.0 -0.4 -0.3
3  -1.9  0.6  1.2
4  -0.2  0.7  0.2
5  -0.6 -0.6 -0.4
6   1.1  0.7 -1.8
7  -0.9  0.6 -0.6
8   1.0  0.5 -0.9
9  -0.4  0.9  1.5
10 -0.5  0.6  2.7
+   sum((x>0)*x)
+ }
+   sum((x<0)*x)
+ }
+   rowwise() |> 
+   mutate(positivos = suma_pos(c_across()),
+          negativos = suma_neg(c_across()))
# A tibble: 10 × 5
# Rowwise: 
       a     b     c positivos negativos
   <dbl> <dbl> <dbl>     <dbl>     <dbl>
 1  -0.1   0.3  -0.4       0.3      -0.5
 2  -1    -0.4  -0.3       0        -1.7
 3  -1.9   0.6   1.2       1.8      -1.9
 4  -0.2   0.7   0.2       0.9      -0.2
 5  -0.6  -0.6  -0.4       0        -1.6
 6   1.1   0.7  -1.8       1.8      -1.8
 7  -0.9   0.6  -0.6       0.6      -1.5
 8   1     0.5  -0.9       1.5      -0.9
 9  -0.4   0.9   1.5       2.4      -0.4
10  -0.5   0.6   2.7       3.3      -0.5