如何使用 dplyr 在数据帧中重复字符串向量 N 次

How to repeat a vector of strings N times in a dataframe using dplyr

我正在处理数据框列表,并希望创建一个包含变量名称的新列。一共有三个变量,dataframe 的长度是 684,因此我需要变量名重复 228 次。但是,我无法让它工作。

这是我目前正在使用的片段:

empleo = lapply(lista.empleo, function(x){x = x %>%
        read_excel(skip=4) %>% 
        head(23) %>% 
        drop_na() %>%
        clean_names() %>% 
        pivot_longer(!1, 
                     names_to = 'fecha',
                     values_to = 'valor') %>% 
        mutate(variable = rep(c('trabajadores',
                                'masa',
                                'salario'), 
                              times = 228))})

到目前为止,我已经尝试使用 mutate,但出现以下错误:

Error in `mutate()`:
! Problem while computing `variable = rep(c("trabajadores", "masa",
  "salario"), times = 228)`.
x `variable` must be size 0 or 1, not 684.

我将在评论中添加示例 df 的结构,因为它太大了。

在此先感谢您的帮助!

rep 可能会失败,因为某些数据集在 list 中的行数可能不同。使用 length.out 确保它 returns n() 个元素(行数)

library(readxl)
library(tidyr)
library(dplyr)
library(janitor)
empleo <- lapply(lista.empleo, function(x){x = x %>%
        read_excel(skip=4) %>% 
        head(23) %>% 
        drop_na() %>%
        clean_names() %>% 
        pivot_longer(!1, 
                     names_to = 'fecha',
                     values_to = 'valor') %>% 
        mutate(variable = rep(c('trabajadores',
                                'masa',
                                'salario'), 
                               228, length.out = n()))})