0

Suppose I have data as follows:

people <- c("John", "Paul", "George", "Ringo", "Mick", "Keith", "Bill", "Charlie", "Brian")

colors <- c("Red", "Blue", "Green", "Red", "Red", "Green", "Green", "Blue", "Blue")

df <- cbind(people, colors)

How can I transform my df such that it extracts the content from the "colors" column and makes it into columns, as below:

Red <- c(1, 0, 0, 1, 1, 0, 0, 0, 0)
Blue <- c(0, 1, 0, 0, 0, 0, 0, 1, 1)
Green <- c(0, 0, 1, 0, 0, 1, 1, 0, 0)

df_dummies <- do.call("cbind", list(people, Red, Blue, Green))
df_dummies

Thanks!

1
  • can a person have only one color assigned? Commented Jun 21, 2022 at 12:46

2 Answers 2

2
data.frame(
  people = people,
  Red = as.integer(colors=="Red"),
  Green = as.integer(colors=="Green"),
  Blue = as.integer(colors=="Blue")
           )
Sign up to request clarification or add additional context in comments.

Comments

1

Base R solution:

with(
  data.frame(df),
  cbind(
    people = people,
    setNames(
      data.frame(+outer(colors, unique(colors),`==`)),
      unique(colors)
    )
  )
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.