view(fastcars)
day car1 car2 car3
1 day1 red silver blue
2 day2 blue red green
3 day3 blue white green
4 day4 green black red
5 day5 black red silver
Took all colors of cars and combined into one list with unique names.
cars <- stack(fastcars[, c(2:4)])
cars <- t(unique(cars[,1]))
Add colors as colnames to end of dataframe
fastcars[c(cars)] <- NA
day car1 car2 car3 red blue green black silver white
1 day1 red silver blue NA NA NA NA NA NA
2 day2 blue red green NA NA NA NA NA NA
3 day3 blue white green NA NA NA NA NA NA
4 day4 green black red NA NA NA NA NA NA
5 day5 black red silver NA NA NA NA NA NA
Would like to fill in NAs with 1 or 0 if the colnames match the variable in columns car1, car2, and/or car3.
day car1 car2 car3 red blue green black silver white
day1 red silver blue 1 1 0 0 1 0
day2 blue red green 1 1 1 0 0 0
day3 blue white green 0 1 1 0 0 1
day4 green black red 1 0 1 1 0 0
day5 black red silver 1 0 0 1 1 0`
I believe this link here is close to what I am trying to do but can't figure out how to create this within my existing dataframe. https://stackoverflow.com/a/30274596/3837899
#Generate example dataframe with character column
example <- as.data.frame(c("A", "A", "B", "F", "C", "G", "C", "D", "E", "F"))
names(example) <- "strcol"
#For every unique value in the string column, create a new 1/0 column
#This is what Factors do "under-the-hood" automatically when passed to function requiring numeric data
for(level in unique(example$strcol)){
example[paste("dummy", level, sep = "_")] <- ifelse(example$strcol == level, 1, 0)
}