【问题标题】:gather() and unite() in tidyrtidyr 中的 collect() 和 unity()
【发布时间】:2018-08-11 15:54:58
【问题描述】:

我在使用 tidyr 的gather() 和 unite() 函数时遇到了一些困难。

这个例子是预期的输出

# 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

但是,使用我的实际数据,我得到了不同的结果。

# 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)

然后我得到这个输出

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  

我做错了什么?

我希望我的实际输出看起来像示例输出。 非常感谢您的帮助。

我想得到这种类型的输出

# 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 

【问题讨论】:

  • 您的第二条gather 评论没有多大意义,您的实际数据表也没有多大意义。根据实际数据表,您的预期输出是什么?
  • 我的数据看起来不再可重现。刚刚添加了我的预期输出。不知道发生了什么。

标签: r tidyr likert


【解决方案1】:

你必须把你的调用方式(数据库,attribute_name,value_variable_name,你收集的列),看起来你错过了命名value_variable_name。下面是基于 iris 的示例

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

【讨论】:

  • 谢谢。我使用了您的代码并针对我的数据进行了调整。我收到此错误原因 Make.names(x) 中的错误:无效的多字节字符串 1。是因为这是一个选择所有适用问题的选项吗?这意味着受访者可以选择多个答案。
  • 很可能您有同名的列会生成此错误
猜你喜欢
  • 2015-05-11
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多