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

Convert long to wide with variable number of columns

$
0
0

Given the following data in long form, I would like to create a wide dataset with one row for each srdr_id, and a separate column for each arm_name as below.

Desired output:

srdr_id c1  c2 c3
174212  TAU MI MI
172612  TAU MI 

I've tried tidyr::spread without success.

   dat <- structure(list(srdr_id = c("174212", "174212", "174212", "172612", 
    "172612"), arm_name = c("TAU", "MI", "MI", "TAU", "MI")), class = c("tbl_df", 
    "tbl", "data.frame"), row.names = c(NA, -5L))

Following the first suggestion, I tried:

dat %>%  group_by(srdr_id) %>% mutate(rn = row_number()) %>% spread(srdr_id, arm_name)

Resulting in:

m  172612 174212
1  TAU    TAU
2  MI     MI
3  NA     MI

I would like the transposed version.


Viewing all articles
Browse latest Browse all 205372

Trending Articles



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