r - How to convert rows into columns using dplyr -


this question has answer here:

i have following data frame (tibble):

library(tidyverse) lines<-" a,foo,9394981 b,bar,6826405 c,qux,1074885 d,gop,1493691    a,foo,100 b,bar,200 c,qux,300 d,gop,400  " con <- textconnection(lines) dat <- read.csv(con,header=false) close(con) dat <- as.tibble(dat) dat 

which looks this:

# tibble: 8 × 3        v1     v2      v3   <fctr> <fctr>   <dbl> 1         foo 9394981 2      b    bar 6826405 3      c    qux 1074885 4      d    gop 1493691 5         foo     100 6      b    bar     200 7      c    qux     300 8      d    gop     400 

how can covert to:

foo        bar    qux     gop 9394981 6826405 1074885 1493691  100     200      300      400 

we can use spread tidyr after creating row index take care of duplicate elements

library(tidyr) library(dplyr) dat %>%     select(-v1) %>%     group_by(v2) %>%    dplyr::mutate(i1 = row_number()) %>%     spread(v2, v3) %>%    select(-i1) 

or using dcast data.table

library(data.table) dcast(setdt(dat), rowid(v2) ~ v2, value.var = "v3")[, v2 := null][] 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -