Skip to content
Back to formatted view

Raw Message

Message-ID: <E49A2E2A-B0E6-45D3-A720-CE9DC8618E10@gmail.com>
Date: 2023-01-02T08:02:16Z
From: Emilio L. Cano
Subject: [R-es] Sumar positivos y negativos por separado
In-Reply-To: <CAF3uytXs=bEyq32YB_7qo_ZBHavgFZwjQnERrwz=zU_V+mhipQ@mail.gmail.com>

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


> set.seed(2023)
> d <- data.frame(a = round(rnorm(10), 1),
+                 b = round(rnorm(10), 1),
+                 c = round(rnorm(10), 1))
> d
      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
> 
> library(dplyr)
> 
> suma_pos <- function(x){
+   sum((x>0)*x)
+ }
> suma_neg <- function(x){
+   sum((x<0)*x)
+ }
> 
> d |> 
+   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



> El 2 ene 2023, a las 6:31, Manuel Mendoza <mmendoza en fulbrightmail.org> escribió:
> 
> Buenos días, de un conjunto de variables, quiero obtener la suma de los
> valores positivos de cada fila, por una parte, y la de los negativos por
> otra. Qué variables toman valores positivos y negativos varía de una fila a
> otra, claro.
> Gracias por vuestra ayuda,
> Manuel
> 
> 	[[alternative HTML version deleted]]
> 
> _______________________________________________
> R-help-es mailing list
> R-help-es en r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-help-es


	[[alternative HTML version deleted]]