【问题标题】:Writing a function with variable times in the repeat function in R在R中的重复函数中编写具有可变时间的函数
【发布时间】:2022-01-19 21:43:06
【问题描述】:

我希望有人可以帮助我编写一个更有说服力的函数来执行以下操作: 假设我有一个大致如下所示的数据框:

library(tidyverse)
d = 
  tibble(
  ID = as.factor(c("1", "2")), 
  dialect_TCU = as.numeric(c(8, 12)), 
  standard_TCU = as.numeric(c(12, 9)), 
  mixture_TCU = as.numeric(c(14, 5))
)

在我的一生中,我无法弄清楚如何编写一个执行以下操作的函数:

  1. 重复每个标题为每个参与者列出的次数,并且
  2. 重复参与者 ID 标头的重复次数。

结束数据框应如下所示:

d2 = 
  tibble(
    ID = c(rep("1", 34), 
           rep("2", 26)),
    successfulRow = c(rep("dialect_TCU", 8), 
                      rep("standard_TCU", 12), 
                      rep("mixture_TCU", 14), 
                      rep("dialect_TCU", 12), 
                      rep("standard_TCU", 9), 
                      rep("mixture_TCU", 5))
  )

如果有人可以帮助我编写一个执行此操作的函数(这可能真的很简单,而且我只是在想整个事情......),那将非常有帮助! 谢谢!

【问题讨论】:

    标签: r function


    【解决方案1】:

    我们可以使用pivot_longer 重塑为“长”,然后使用uncount 复制行

    library(dplyr)
    library(tidyr)
    d %>% 
      pivot_longer(cols = -ID, names_to = "successfulRow") %>%
      uncount(value)
    

    -输出

    # A tibble: 60 × 2
       ID    successfulRow
       <fct> <chr>        
     1 1     dialect_TCU  
     2 1     dialect_TCU  
     3 1     dialect_TCU  
     4 1     dialect_TCU  
     5 1     dialect_TCU  
     6 1     dialect_TCU  
     7 1     dialect_TCU  
     8 1     dialect_TCU  
     9 1     standard_TCU 
    10 1     standard_TCU 
    # … with 50 more rows
    

    【讨论】:

      猜你喜欢
      • 2015-09-12
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      相关资源
      最近更新 更多