【问题标题】:Is there a way to move every other row in a column into a new column in R?有没有办法将列中的每隔一行移动到 R 中的新列中?
【发布时间】:2020-07-29 01:10:32
【问题描述】:

挑战:我有一列有几行。例如,第一行是“水果名称”,第二行是“水果颜色”,它对另一个水果重复。我想抓住每隔一行(水果颜色)并创建一个新列。在原始列中只保留水果名称

library(tidyverse)
df_before <- tribble(~Singlecolumn,"Apple","Red","Banana","Yellow","Kiwi","Grey","Grapes","Green")
df_before
Singlecolumn
<chr>
Apple               
Red             
Banana              
Yellow              
Kiwi                
Grey                
Grapes              
Green

#I would like to split this like below:
df_after <- tribble(~Column1, ~Column2, "Apple","Red","Banana","Yellow","Kiwi","Grey","Grapes","Green")
df_after

Column1 Column2
Apple   Red         
Banana  Yellow          
Kiwi    Grey            
Grapes  Green

我确信有一种更简单的方法可以使用 tidyverse 中的函数来执行此操作,但无法通过大量搜索找到任何信息。 将不胜感激任何指针。提前致谢!

【问题讨论】:

    标签: r dplyr tidyverse tidyr purrr


    【解决方案1】:

    我们可以使用逻辑值的向量循环来从df_before获取备用数据。

    data.frame(Column1 = df_before$Singlecolumn[c(TRUE, FALSE)], 
               Column2 = df_before$Singlecolumn[c(FALSE, TRUE)])
    
    #  Column1 Column2
    #1   Apple     Red
    #2  Banana  Yellow
    #3    Kiwi    Grey
    #4  Grapes   Green
    

    【讨论】:

    • 优雅的解决方案。我不知道矢量回收。
    【解决方案2】:

    您可以通过索引奇数和偶数列来做到这一点

    # dummy data (please provide code to make a reproducible example in the future)
    df1 <- data.frame(v1 = c("A", "a", "B", "b", "C", "c"))
    # solution 
    df2 <- data.frame(
      "col1" = df1[seq(1,length(df1[,1]),2), "v1"], 
      "col2" = df1[seq(2,length(df1[,1]),2), "v1"])
    

    这里的序列用于给出一个由 2 分隔的整数向量,使用 seq() 函数从 1 或 2 运行到原始数据帧的长度,例如

    seq(2,length(df1[,1]),2)
    ## [1] 2 4 6
    

    然后将其传递到 df[rows, columns] 的方括号中的行。

    【讨论】:

      【解决方案3】:

      更简单的选择是转换为具有 2 列的 matrix,然后在 base R 中转换为 data.frame

      as.data.frame(matrix(df_before$Singlecolumn, ncol = 2, byrow = TRUE))
      

      但是,我们也可以使用tidyverse,使用rep 创建两个组,然后使用pivot_wider 将“长”格式重塑为“宽”格式

      library(dplyr)
      library(tidyr)
      df_before %>%
        group_by(grp = str_c('Column', rep(1:2, length.out = n()))) %>%
        mutate(rn = row_number()) %>%
        ungroup %>%
        pivot_wider(names_from = grp, values_from = Singlecolumn) %>%
        select(-rn)
      # A tibble: 4 x 2
      #  Column1 Column2
      #  <chr>   <chr>  
      #1 Apple   Red    
      #2 Banana  Yellow 
      #3 Kiwi    Grey   
      #4 Grapes  Green  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-15
        • 1970-01-01
        • 2020-11-25
        • 2020-12-19
        • 2021-08-22
        相关资源
        最近更新 更多