【发布时间】:2020-10-20 18:28:31
【问题描述】:
这可能看起来有点微不足道,但我正在尝试根据另一列中的 id 生成 id。但是,新的 id 应该基于公式构建,并且应该为第一列中的每个 id 递增 1:5。
所以是这样的:
list_ids_2 <- tibble(id = rep(c(12345, 34564, 234521, 90889), each = 5))
# For each id in `list_ids_2` there should be 5 ids
# with this formula (100*(id + 1200) + j),
# where j starts at 1 and increases until 5
# at which point it moves to the next id and does the #same thing again.
#This works only in the sense that it produces 20 new ids. Ideally though, the initial ids #(above) wouldn't already have to be replicated 5 times.
list_ids_2$new_id <- 0
for (i in unique(list_ids_2$id)) {
#print(i)
for (j in 1:5){
#print(j)
b <- (( 100 * (i + 1200) + j))
print(b)
#list_ids_2$new_id[1,1] <- b
}
}
[1] 124234501
[1] 124234502
[1] 124234503
[1] 124234504
[1] 124234505
[1] 126456401
[1] 126456402
[1] 126456403
[1] 126456404
[1] 126456405
[1] 146452101
[1] 146452102
[1] 146452103
[1] 146452104
[1] 146452105
[1] 132088901
[1] 132088902
[1] 132088903
[1] 132088904
[1] 132088905
#Adding this to the list_ids_2 tibble doesn't work though.
这也适用,但不会增加数字1:5
generator <- function(x){
j <- 1
while(j <= 5){
b <- (( 100 * (x + 1200) + j))
j <- j + 1
return(b)
print(b)
}
}
generator(c(1234,1234))
[1] 123123401 123123401
理想情况下,我会从一个数据框开始,可能必须以一个新的数据框/tibble b/c 维度结束,这就是为什么不能将结果添加到 list_ids_2 tibble .
非常感谢任何帮助!
【问题讨论】:
-
你能给出一个期望输出的样本吗?
标签: r