Reputation: 69
I have this dataset:
ID <- c("0001", "0003", "0002","0004","0005")
YourName <- c("Juan", "Pedro", "Ana", "Alejandra","Alex")
GenderPeople <- c("Male","Male","Female","Female","Male")
DF <- data.frame(ID, YourName, GenderPeople)
I want to convert column "GenderPeople" into a matrix (or dataframe) that looks like this:
ID YourName GenderPeople_Male GenderPeople_Female
0001 Juan 1 0
0003 Pedro 1 0
0002 Ana 0 1
0004 Alejandra 0 1
0005 Alex 1 0
Thank you very much for your help.
Greetings!
Upvotes: 0
Views: 30
Reputation: 16121
library(dummies)
dummy.data.frame(DF, names = "GenderPeople", sep = "_")
# ID YourName GenderPeople_Female GenderPeople_Male
# 1 0001 Juan 0 1
# 2 0003 Pedro 0 1
# 3 0002 Ana 1 0
# 4 0004 Alejandra 1 0
# 5 0005 Alex 0 1
Upvotes: 2
Reputation: 887741
We can use spread
after creating a column of 1s
library(tidyverse)
DF %>%
mutate(n = 1, GenderPeople = str_c("GenderPeople", GenderPeople, sep="_")) %>%
spread(GenderPeople, n, fill = 0)
# ID YourName GenderPeople_Female GenderPeople_Male
#1 0001 Juan 0 1
#2 0002 Ana 1 0
#3 0003 Pedro 0 1
#4 0004 Alejandra 1 0
#5 0005 Alex 0 1
Upvotes: 2