Search code examples
rtidyrlikert

gather() and unite() in tidyr


I am running into a bit of a wall using the gather() and unite() functions from tidyr.

This example is the intended output

# sample Data
> wide_df 
    col A   B  C 
1   X   1   2  3 
2   Y   4   5  6

> gather(wide_df, my_key, my_val, -col)
  col my_key my_val
1  X   A      1 
2  Y   A      4 
3  X   B      2 
4  Y   B      5 
5  X   C      3 
6  Y   C      6

However, using my actual data, I get a different result.

# Actual Data
>Parents_Pulse_Survey
    col         Too_demanding       Cost_Too_High   Prefer_Stay_ParentHome
1   Austin     NA                   NA             Prefer_Stay_ParentHome
2   Austin     Too_demanding        NA                 NA

reasons <-gather(Austin_Parent_Pulse_Survey, reasonsWhy,High_Childcare_Cost:Other_Stay_At_Home)

Then I get this output

reasons
# A tibble: 30,900 x 2
   reasonsWhy `High_Childcare_Cost:Other_Stay_At_Home`
   <chr>      <chr>                                   
 1 Austin     Yes                                     
 2 Austin     Yes                                     
 3 Austin     Yes                                     
 4 Austin     Yes                                     
 5 Austin     Yes                                     
 6 Austin     Yes  

What am I doing wrong?

I want my actual output to look like the sample output. Your help is greatly appreciated.

I would like to get this type of output

# Intended Output
reasons         
   Respondent      Reasons                                   
 1 Austin          High_Childcare_Cost                                    
 2 Austin          Other_Stay_At_Home                                    
 3 Austin          Too_demanding                                     
 4 Austin          Too_demanding                                     
 5 Austin         High_Childcare_Cost                                      
 6 Austin         Other_Stay_At_Home 

Solution

  • You have to put how you call (database, attribute_name, value_variable_name, columns you collect), looks like you miss to name value_variable_name. Below is example based on iris

     str(iris)
     reasons <- gather(iris, 
                       reasonsWhy, Value,
                       Sepal.Length:Petal.Width)