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

How to go from long to wide dataframe in R with multiple values separated by a comma in focal column

$
0
0

Say I have a list of movies with their directors. I want to convert these directors to dummy variables (i.e. if a director directs a movie, they have their own column with a 1, if they don't direct that movie then that column has a zero). This is tricky because there are occasionally movies with two directors. See example below. df is the data I have, df2 is what I want.

movie <- c("Star Wars V", "Jurassic Park", "Terminator 2")
budget <- c(100,300,400)
director <- c("George Lucas, Lawrence Kasdan", "Steven Spielberg", "Steven Spielberg")

df <- data.frame(movie,budget,director)
df

movie <- c("Star Wars V", "Jurassic Park", "Terminator 2")
budget <- c(100,300,400)
GeorgeLucas <- c(1,0,0)
LawrenceKasdan <- c(1,0,0)
StevenSpielberg <- c(0,1,1)

df2 <- data.frame(movie, budget, GeorgeLucas, LawrenceKasdan, StevenSpielberg)
df2

Viewing all articles
Browse latest Browse all 201977

Trending Articles



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