如何创建带对应编号的重复字符串向量:生成user_1至user_33适配purrr函数.y参数
user_1 to user_33 Vector for purrr's .y Argument Got it, let's get this sorted for you! You're aiming to generate a vector of strings like user_1, user_2, ..., user_33 to pass as the .y parameter in a purrr function—your initial rep(user_, [1:33]) approach isn't working because rep() repeats existing elements, but you need to combine the base string with sequential numbers instead.
Here are the simplest ways to make this vector:
1. Base R with paste0()
This is the most straightforward method using base R, no extra packages needed:
user_vec <- paste0("user_", 1:33)
paste0() concatenates strings without any separator, so it perfectly pairs "user_" with each number from 1 to 33.
2. Tidyverse-friendly with stringr::str_c()
If you're already using purrr (part of the tidyverse), str_c() from the stringr package is a great alternative—it works the same way but fits better with tidyverse workflows:
library(stringr) user_vec <- str_c("user_", 1:33)
Using this vector with purrr
Once you have user_vec, you can pass it directly to purrr functions. For example, if you want to map a function over each user ID:
library(purrr) # Example function to process a user ID process_user <- function(user_id) { message("Working on: ", user_id) } # Pass user_vec as .y (or as the first argument to map, which defaults to .x) map(.y = user_vec, .f = process_user) # Or the more common shorthand: map(user_vec, process_user)
Why your initial rep() approach didn't work
The rep(user_, 1:33) syntax would repeat the string user_ 1 time, then 2 times, up to 33 times—resulting in a vector like c("user_", "user_", "user_", ...) (total of 1+2+...+33 = 561 elements) instead of the numbered sequence you need.
内容的提问来源于stack exchange,提问作者Stackstudent_09

