【问题标题】:R - Converting dataframe from long to wide format with multiple value columnsR - 将数据帧从长格式转换为具有多个值列的宽格式
【发布时间】:2021-06-21 15:16:34
【问题描述】:

全部。

对 R 非常陌生,并且可以更广泛地处理数据。也从未在 Stack Overflow 或类似内容中写过任何东西,因此请原谅任何不可靠的格式或术语。

我有一个需要从长格式转换为宽格式的数据框,为配对 T 检验做好准备。数据框为:

> head(df)
# A tibble: 6 x 13
  Assessor Product               Ap    Ar       F       T
     <dbl> <chr>               <dbl> <dbl>   <dbl>   <dbl>
1        1 MC                    10    10      10      10
2        1 MV                    10    10      10      10
3        2 MC                     6     7       8       8
4        2 MV                     7     5       4       8
5        3 MV                     9     9      10       9
6        3 MC                     6     8       7       6
# ... with 7 more variables:
#   C1 <dbl>,
#   JCo <dbl>,
#   JSt1 <dbl>,
#   JSt2 <dbl>,
#   JSw <dbl>,
#   JCr <dbl>,
#   OA <dbl>

我需要将它放在以下宽格式中,但对于所有变量,其中 Product 之后的每一列都转换为两列,每个产品一列(MC 和 MV):

  Assessor  Ap_MC  Ap_MV  Ar_MC   Ar_MV      
     <dbl>   <dbl>  <dbl>  <dbl>   <dbl>  
1        1    10     10      10      10   
2        2     6      7       7       5    
3        3     9      6       9       8  

标题不一定是这些,但需要区分它们是按不同产品以及原始列分组的。

我在这里看到了各种在长格式和宽格式之间转换的方法,但我无法进行任何工作。这是我使用 pivot_wider() 所做的尝试(包括错误消息):

df <- pivot_wider(df, id_cols = df[1], names_from = df[2], values_from = df[3:13])

Error: Must subset columns with a valid subscript vector.
x Subscript has the wrong type `tbl_df<Product:character>`.
i It must be numeric or character.
Run `rlang::last_error()` to see where the error occurred.

我不知道是什么导致了这个错误,更不用说我的尝试是否接近给我想要的输出了。

提前谢谢你!

【问题讨论】:

标签: r


【解决方案1】:

您的解决方案实际上非常接近!唯一的问题是pivot_wider 足够聪明,可以只接受列名作为输入。换句话说,与其将 df[1](实际列)作为 id_cols 传递,我们应该只传递列的名称 Assessor

df = data.frame(Assessor=c(1,1,2,2), Product=c('MC', 'MV', 'MC', 'MV'), App=c(1,2,3, 3), Ar=c(4,5,6, 6))

pivot_wider(df, id_cols = Assessor, names_from = Product, values_from = c('App', 'Ar'))
  Assessor  Ap_MC  Ap_MV  Ar_MC   Ar_MV      
     <dbl>   <dbl>  <dbl>  <dbl>   <dbl>  
1        1    10     10      10      10   
2        2     6      7       7       5    

通常,在使用 tidyverse 中的函数时,您按名称引用列(通常不加引号)。

解释错误:

我们在错误消息中得到了问题的提示。您可以看到错误与我们选择列的方式有关(具有有效下标向量的子集列)。它告诉我们我们的下标是 tbl_df 类型(它甚至告诉我们名称“产品”),而实际上它所期望的是数字(列索引)或字符(列名)

附:你的格式很棒。

【讨论】:

  • 感谢您的回复。使用列号引用没有直接的方法吗?我知道我只有 13 列,而且大多数变量都很短,但这似乎仍然效率低下且容易出错,尤其是在列更多和/或名称更长的情况下。
  • 当然,您可以按名称或索引来引用列。所以在这种情况下你可以使用...values_from = 3:ncol(df)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-22
  • 1970-01-01
  • 2023-02-25
  • 2021-10-08
相关资源
最近更新 更多