假设我有一个清单
x <- as.list(c("john","jerry","james"))
Run Code Online (Sandbox Code Playgroud)
和值列表
y <- as.list(c(8,5,10))
Run Code Online (Sandbox Code Playgroud)
我想遍历x的第一个元素,y的第一个元素的次数,并在最后添加一个后缀。因此,对于元素john,它将为john_1,john_2 ... john_8。那么jerry就是jerry_1,jerry_2 ... jerry_5。还有james_1,james_2,...,james_10
这是我尝试过的不起作用的
z <- lapply(x, function(i){paste(i,"_",rep(max))})
Run Code Online (Sandbox Code Playgroud)
但这并不能满足我的需求。
也许,我不应该使用lapply或map *的某些版本,但不要在这些基础上进行工作。
An idea via base R,
Map(function(x, y)paste0(x, '_', seq(y)), x, y)
#[[1]]
#[1] "john_1" "john_2" "john_3" "john_4" "john_5" "john_6" "john_7" "john_8"
#[[2]]
#[1] "jerry_1" "jerry_2" "jerry_3" "jerry_4" "jerry_5"
#[[3]]
# [1] "james_1" "james_2" "james_3" "james_4" "james_5" "james_6" "james_7" "james_8" "james_9" "james_10"
Run Code Online (Sandbox Code Playgroud)