R:为什么我会使用spread()丢失数据?

问题描述 投票:0回答:1

我有一个看起来像这样的东西。

# A tibble: 1,000 x 3
   id                 question                               answer                                                          
   <chr>                  <chr>                                <chr>                                                                     
 1 aaa               What is your favorite color?                Green                                                                        
 2 aaa               What is your favorite band?                 Green Day                                                       
 3 aaabb             What is your favorite color?                Blue                                                                                
 4 aaabb             What is your favorite band?                Blue            
 5 ccc               What is your favorite color?                Blue                                                                        
 6 ccc               What is the difference between you and me?  Five bank accounts                                             
# ... with more rows

我想将它扩展为一个广泛的数据框架。我用过这段代码。

aTibble %>% distinct() %>%  spread(question, answer)

但是,我最终得到一个充满空行的数据框。

  # A tibble: 1,000 x 3
       id                 V1              What is your favorite color?   What is your favorite band?   What is the difference between you and me?                                                 
     1 aaa                               NA                              NA                            NA                                                        
     2 aaa                               NA                              NA                            NA                         
     3 aaabb                             NA                              NA                            NA                                                
     4 aaabb                             NA                              NA                            NA
     5 ccc                               NA                              NA                            NA                                          
     6 ccc                               NA                              NA                            NA               
    # ... with more rows

在原始tibble中,一些行具有ID,然后为问题和答案为null。单个ID没有重复的问题。也就是说,不同的ID可以回答不同的问题,但它们并不都有相同的问题。

另外,我没有制作V1行,这不是我原来的tibble。它出现在spread()之后。

令人沮丧的是,当我在一个小数据集上执行该功能时,它工作得很好。当我在完整数据集(~150K记录)上执行该功能时,我得到了NA。

r dplyr data-cleaning spread
1个回答
2
投票

很难理解为什么这样做不起作用。 dcast是使用reshape2的好选择。你可以实现同样的目标。

aTibble %>% distinct() %>% dcast(id ~ question, value.var = "answer")
© www.soinside.com 2019 - 2024. All rights reserved.