'How do I pivot a data frame wider turning a variable of numbers (e.g. election years) into dichotomous variables
I have a data frame of election survey data. One variable lists the year of the election, other variables report individual level data (e.g. vote choice, gender).
How do I turn the variable that contains the election year (in this case var1) into a series of dichotomous variables. I can do this with a series of Recodes, but I'd like to make pivot_wider work here.
var1<-sample(seq(1,5, 1), size=500, replace=T)
var2<-sample(c("red", "orange"), size=500, replace=T)
var3<-sample(c(0,1), size=500, replace=T)
df<-data.frame(var1, var2, var3)
library(tidyverse)
df
df %>%
pivot_wider(., names_from=var1, values_from=var1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
