Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pivot_wider when there's no value column

Tags:

r

tidyverse

I'm trying to reshape a dataset from long to wide. The following code works, but I'm curious if there's a way not to provide a value column and still use pivot_wider. In the following example, I have to create a temporary column "val" to use pivot_wider, but is there a way I can do it without it?

a <- data.frame(name = c("sam", "rob", "tom"),
                 type = c("a", "b", "c"))
a
  name type
1  sam    a
2  rob    b
3  tom    c

I want to convert it as the following.

name      a     b     c
1 sam       1     0     0
2 rob       0     1     0
3 tom       0     0     1 

This can be done by the following code, but can I do it without creating "val" column (and still using tidyverse language)?

a <- data.frame(name = c("sam", "rob", "tom"),
                type = c("a", "b", "c"), 
                val = rep(1, 3)) %>%
  pivot_wider(names_from = type, values_from = val, values_fill = list(val = 0))
like image 685
qnp1521 Avatar asked Mar 04 '20 22:03

qnp1521


People also ask

How does Pivot_wider work in R?

pivot_wider() is the opposite of pivot_longer() : it makes a dataset wider by increasing the number of columns and decreasing the number of rows. It's relatively rare to need pivot_wider() to make tidy data, but it's often useful for creating summary tables for presentation, or data in a format needed by other tools.

What package is Pivot_wider in?

The pivot_wider() function from the tidyr package in R can be used to pivot a data frame from a long format to a wide format.


2 Answers

You can use the values_fn argument to assign 1 and values_fill to assign 0:

library(tidyr)

pivot_wider(a, names_from = type, values_from = type, values_fn = list(type = ~1), values_fill = list(type = 0))

# A tibble: 3 x 4
  name      a     b     c
  <fct> <dbl> <dbl> <dbl>
1 sam       1     0     0
2 rob       0     1     0
3 tom       0     0     1
like image 132
Ritchie Sacramento Avatar answered Nov 16 '22 00:11

Ritchie Sacramento


We can mutate with a column of 1s and use that in pivot_wider

library(dplyr)
library(tidyr)
a %>%
     mutate(n = 1) %>% 
     pivot_wider(names_from = type, values_from = n, values_fill = list(n = 0))
# A tibble: 3 x 4
#  name      a     b     c
#  <fct> <dbl> <dbl> <dbl>
#1 sam       1     0     0
#2 rob       0     1     0
#3 tom       0     0     1

In base R, it would be easier..

table(a)
like image 20
akrun Avatar answered Nov 16 '22 01:11

akrun