0

I have a data frame that looks like this :

name var1 var2 var3
a 1 10 -1
a 2 20 -2
a 3 30 -3
b 4 40 -4
b 5 50 -5
b 6 60 -6
c 7 70 -7
c 8 80 -8
c 9 90 -9

I want to sum of the sub matrices according to name variable but rowwise in one matrix keeping the column name. (Not to sum all the values in the group a or b).

ideally I want the resulted data frame to look like this :

var1 var2 var3
12 120 -12
15 150 -15
18 180 -18

how can I do this in R using dplyr ?

 library(tidyverse)
name = c(rep("a",3),rep("b",3),rep("c",3))
var1 = seq(1,9,1);var1
var2 = seq(10,90,10);var2
var3 = seq(-1,-9,-1);var3
A = tibble(name,var1,var2,var3);A

Homer Jay Simpson
  • 1,043
  • 6
  • 19
  • I put an answer that I came up after the question is closed: `map_dfr(.x=c(1,2,0),~slice(A,which(row_number()%%3==.x))|>summarise(across(var1:var3,sum)))` – Carlos Luis Rivera Oct 16 '22 at 10:50
  • @CarlosLuisRivera when I run your answer R reported me the following : `Error in `as_mapper()`: ! Can't convert `.f`, a object, to a function.` – Homer Jay Simpson Oct 16 '22 at 10:52
  • why you deleted my question ? the suggested answers from previous posts are not equivalent – Homer Jay Simpson Oct 16 '22 at 10:55
  • 1
    I did not close your question, rather I flagged your question to reopen it. Not only you but I don't know why other moderators/users closed your question. – Carlos Luis Rivera Oct 16 '22 at 10:57
  • 1
    @CarlosLuisRivera thank you for that.I cannot understand why someone votes to close a question that believes there is an answer somewhere else.I tried it.I searched for a question.I didn't find one so a make a post. – Homer Jay Simpson Oct 16 '22 at 10:59
  • I'm not sure why my code throw any error, since the code works in my environment. I use `tibble 3.1.8`, `dplyr 1.0.10`, and `purrr 0.3.4` on R 4.2.0. What is the version number of these three packages on your environment? What verseon of R are you using? – Carlos Luis Rivera Oct 16 '22 at 11:03
  • 1
    @CarlosLuisRivera on `R version 4.1.1 (2021-08-10)` I run `tibble_3.1.7` , `dplyr_1.0.9` and `purrr_0.3.4` – Homer Jay Simpson Oct 16 '22 at 11:09
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/248842/discussion-between-carlos-luis-rivera-and-homer-jay-simpson). – Carlos Luis Rivera Oct 16 '22 at 11:12
  • @CarlosLuisRivera speechless.Thank you for your help.You are awesome.Still the question remains deleted.hahahha – Homer Jay Simpson Oct 17 '22 at 16:27

0 Answers0