Quantcast
Channel: Convert a columns into separate columns in wide format in R - Stack Overflow
Viewing all articles
Browse latest Browse all 6

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

$
0
0

Here is an approach using unnest_wider():

library(purrr)library(dplyr)library(tidyr)data %>%   mutate(FRUITS = map(FRUITS, ~ set_names(levels(factor(FRUITS)) == .x, levels(factor(FRUITS))))) %>%   unnest_wider(FRUITS)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 

Here is a slightly adapted version using values_fn:

library(dplyr)library(tidyr)data %>%   mutate(row_id = row_number()) %>%   pivot_wider(names_from = FRUITS, values_from = FRUITS,               values_fn = list(FRUITS = ~length(.x) > 0),               values_fill = FALSE) %>%   select(-row_id)
 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

For this specific example and without generalizability

library(dplyr)data %>%   mutate(Apple = FRUITS == "Apple", Banana = FRUITS == "Banana")

Viewing all articles
Browse latest Browse all 6

Trending Articles



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