【问题标题】:convert one column of many rows into many columns将多行的一列转换为多列
【发布时间】:2022-11-17 20:26:19
【问题描述】:

我在一个文件中有两列,就像这样

Column A Column B
Apple 2
Bat 2
Cat 4
Bat 2.5
Apple 6
Cat 4.8

我想将 A 列值转换为单独的列和 B 列中的相应值

Apple Bat Cat
2 2 4
6 2.5 4.8

【问题讨论】:

    标签: r


    【解决方案1】:

    对于您的数据,我们可以这样做:

    最重要的是用 n(在本例中为 3)创建组,我们使用 gl() 函数对第一行进行创建,然后使用 pivot_wider:

    library(dplyr)
    library(tidyr)
    
    df %>% 
      mutate(col2 =as.integer(gl(n(),3,n()))) %>% 
      pivot_wider(names_from = ColumnA, values_from=ColumnB) %>% 
      select(-col2)
    
      Apple   Bat   Cat
      <dbl> <dbl> <dbl>
    1     2   2     4  
    2     6   2.5   4.8
    > 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-01
      • 2017-08-14
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多