0

I have a data that looks like this:

enter image description here it can be build using codes:

df<-structure(list(`Hobby 1` = c("Drawing", NA, "Singing", "drawing"
), `Hobby 2` = c(NA, NA, "reading", "singing"), `Hobby 3` = c(NA, 
NA, NA, "reading")), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame"))

Is it a way I can build a summary varaible for it that will looks like this: enter image description here

1

2 Answers 2

2

unite from ‘tidyr’ does this almost out of the box:

〉df %>% unite(Hobby, `Hobby 1` : `Hobby 3`, sep = ', ', na.rm = TRUE)
# A tibble: 4 x 1
  Hobby
  <chr>
1 "Drawing"
2 ""
3 "Singing, reading"
4 "drawing, singing, reading"

So, with minimal post-processing:

df %>%
    unite(
        Hobby, `Hobby 1` : `Hobby 3`,
        sep = ', ',
        na.rm = TRUE,
        remove = FALSE
    ) %>%
    mutate(Hobby = ifelse(nzchar(Hobby), paste('Hobby:', Hobby), 'No Hobby'))
Sign up to request clarification or add additional context in comments.

Comments

1

Or, in base R:

df$Hobby <- paste("Hobby:", sub("NA", "None", gsub(", NA", "", 
            apply(df, 1, paste, collapse = ", "))))

df
#>   Hobby 1 Hobby 2 Hobby 3                            Hobby
#> 1 Drawing    <NA>    <NA>                   Hobby: Drawing
#> 2    <NA>    <NA>    <NA>                      Hobby: None
#> 3 Singing reading    <NA>          Hobby: Singing, reading
#> 4 drawing singing reading Hobby: drawing, singing, reading

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.