Here are a few options.
Option 1: We could use .table data merging after re-casting the molten data.
library(data.table) # v1.9.6 ## make 'df' a data.table setDT(df) ## melt, cast, and merge on 'day' df[dcast(melt(df, "day"), day ~ value, fun.aggregate = length), on = "day"] # day car1 car2 car3 black blue green red silver white # 1: day1 red silver blue 0 1 0 1 1 0 # 2: day2 blue red green 0 1 1 1 0 0 # 3: day3 blue white green 0 1 1 0 0 1 # 4: day4 green black red 1 0 1 1 0 0 # 5: day5 black red silver 1 0 0 1 1 0
Option 2: Below is a less attractive, but reasonable approach to base R.
#
Data:
df <-structure(list(day = structure(1:5, .Label = c("day1", "day2", "day3", "day4", "day5"), class = "factor"), car1 = structure(c(4L, 2L, 2L, 3L, 1L), .Label = c("black", "blue", "green", "red"), class = "factor"), car2 = structure(c(3L, 2L, 4L, 1L, 2L), .Label = c("black", "red", "silver", "white"), class = "factor"), car3 = structure(c(1L, 2L, 2L, 3L, 4L), .Label = c("blue", "green", "red", "silver" ), class = "factor")), .Names = c("day", "car1", "car2", "car3"), class = "data.frame", row.names = c("1", "2", "3", "4", "5"))