Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Pivot data from wide to long using column suffix to get table with multiple columns with values (using pivot_longer)

$
0
0

I have a tibble/dataframe that looks like this:

hc_inpatient_sum hc_ambulant_sum hc_inpatient_mean hc_ambulant_mean
5                2               5.5              2.2

My desired output is:

my_names       sum  mean
hc_inpatient     5   5.5
hc_ambulant      2   2.2

I get what I want using the following code. However, it seems pretty complicated. I guess that the same result could be obtained using less complicated code.

library(dplyr)
library(tidyr)

my_data <- tibble(hc_inpatient_sum = 5, hc_ambulant_sum = 2, hc_inpatient_mean = 5.5, 
hc_ambulant_mean = 2.2)

res <- my_data %>% 
  pivot_longer(cols = everything(), names_to = "my_names", values_to = "my_values") %>% 
  separate(my_names, into = c("my_names", "stats"), sep = "_(?=[^_]+$)") %>% 
  pivot_wider(names_from = "stats", values_from = "my_values")

Is there a more direct way to get the same result using tidyr::pivot_longer?

Alternatively I could do something like this...

res2 <- pivot_longer(my_data, cols = everything(),
             names_to = c(".value", "stats"), 
             names_pattern = "(.*)_(.*)") %>% 
  t()

colnames(res2) <- res2["stats",]

res2 <- as_tibble(res2[-1,], rownames = "my_names") %>% 
  mutate_at(vars(-my_names), as.double)

... but that is even more awkward.


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>