Adding a column to a data frame

Hi, and welcome!

Check out the homework policy for this site. We don't provide answers, for obvious reasons, but I can offer you a pointer to get you started. Also, learn to include a reproducible example, called a reprex.

You've got the first step--creating a new column, and now you're stuck on the second step, filling it it, right? There are a couple of techniques you can use for this.

The first, which is more cumbersome, is to use a for loop to examine the values in each row until you get a hit, then stopping. To do this you would pipe your dataframe, which I will call movies into mutate with an ifelse test. Something like

movies %>% mutate(genre = ifelse(Action == 1, "Action, NA")) ...

repeat for each column until you get a hit, then stop.

The second way is to treat each row as a logical vector, find the position of the first TRUE and use that as an index to get the corresponding genre:

genres <- c("Action", "Animation", "Comedy", "Documentary", "Romance", "Short")
row_vector <- c(0,0,1,1,0,0,0)
indices <-min(which(row_vector == TRUE))
#> [1] "Comedy"

Created on 2019-12-17 by the reprex package (v0.3.0)

Try combining that algorithm with mutate to populate Genre

1 Like