Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert column names into row values and find sum

Tags:

r

I have this data frame-

input_output <- data.frame(ip_op = c('input_0', 'input_2', 'input_9', 'output_1', 'output_2', 'output_3'), a = c(1,32, 12, 246, 901, 837), b = c(284, 23, 19, 284, 9, 12), c = c(12, 8940, 379, 490, 0, 12))

ip_op   a   b    c
1  input_0   1 284   12
2  input_2  32  23 8940
3  input_9  12  19  379
4 output_1 246 284  490
5 output_2 901   9    0
6 output_3 837  12   12

I want to create the following data frame-

input_output
  type input output
1    a    45   1984
2    b   326    305
3    c  9331    502

I have tried using transpose but the column names become rownames. How do I transform this data frame?

like image 312
Misha Avatar asked Dec 30 '22 20:12

Misha


1 Answers

Does this work:

> library(dplyr)
> library(tidyr)    
> input_output %>% pivot_longer(-ip_op) %>% mutate(ip_op = str_extract(ip_op, ('input|output'))) %>% group_by(ip_op, name) %>% summarise(value = sum(value)) %>% 
+  pivot_wider(names_from = ip_op, values_from = value) %>% rename(type = name)
`summarise()` regrouping output by 'ip_op' (override with `.groups` argument)
# A tibble: 3 x 3
  type  input output
  <chr> <dbl>  <dbl>
1 a        45   1984
2 b       326    305
3 c      9331    502
> 
like image 174
Karthik S Avatar answered Jan 18 '23 07:01

Karthik S