Quantcast
Viewing all articles
Browse latest Browse all 6

Answer by stefan for Convert a columns into separate columns in wide format in R

To reshape to wide using tidyr::pivot_wider you have to add a value column to your dataset and a column with a unique id for each row:

df <- data.frame(  Gender = c("Female", "Female", "Female", "Male", "Female", "Female"),  AgeGroup = c("30yr_39yr", "20yr_29yr", "70yr_80yr", "50yr_59yr", "40yr_49yr", "70yr_80yr"),  EAT = c("Yes", "Yes", "Yes", "Yes", "Yes", "Yes"),  FRUITS = c("Apple", "Apple", "Apple", "Banana", "Apple", "Apple"))library(tidyr)library(dplyr, warn = FALSE)df |>  mutate(    value = TRUE,    id = row_number()  ) |>  pivot_wider(    names_from = FRUITS,    values_from = value, values_fill = FALSE  ) |>  select(-id)#> # A tibble: 6 × 5#>   Gender AgeGroup  EAT   Apple Banana#>   <chr>  <chr>     <chr> <lgl> <lgl> #> 1 Female 30yr_39yr Yes   TRUE  FALSE #> 2 Female 20yr_29yr Yes   TRUE  FALSE #> 3 Female 70yr_80yr Yes   TRUE  FALSE #> 4 Male   50yr_59yr Yes   FALSE TRUE  #> 5 Female 40yr_49yr Yes   TRUE  FALSE #> 6 Female 70yr_80yr Yes   TRUE  FALSE

Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>