PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 6, 2022

[FIXED] How to separate or unnest several variables in a character column

 October 06, 2022     pivot, r, statistics, tidyr, tidyverse     No comments   

Issue

I have a multiple choice question from my survey that has several character variables per line. I was trying to figure out how I can separate these using tidyverse, so I can use ggplot2 to put the total answers for each variable in a bar graph.

Example:

What are your preferred methods for receiving information about precision technologies and conservation programs and incentives? (Select up to 3)

df <- data.frame (Name  = c("Sue", "Joe", "Bob"),
                  Q3 = c("Mail,Live Demonstrations,Websites", "Mail,Websites,In-person meetings/seminars", "Email,Mail,Videos (Ex: Youtube)"))

I tried pivot_longer(Survey$Q3) (with Q3 being the answers) but I got back this error

"Error in UseMethod("pivot_longer") : 
  no applicable method for 'pivot_longer' applied to an object of class "character""

Solution

You can str_split the column then unnest:

df %>%
  as_tibble() %>%
  mutate(Q3 = str_split(Q3, ",")) %>%
  unnest(Q3)

# # A tibble: 9 × 2
#   Name  Q3                         
#   <chr> <chr>                      
# 1 Sue   Mail                       
# 2 Sue   Live Demonstrations        
# 3 Sue   Websites                   
# 4 Joe   Mail                       
# 5 Joe   Websites                   
# 6 Joe   In-person meetings/seminars
# 7 Bob   Email                      
# 8 Bob   Mail                       
# 9 Bob   Videos (Ex: Youtube)


Answered By - dcsuka
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing