如何防止R代码中的sprintf错误

如何防止R代码中的sprintf错误,r,R,我有一个有几列的数据框。每当第V2列的行值小于20时,第V4列中同一行上的字符元素将替换为字符串“sp_nameofOpelement_nameofBottomeElement” 我的代码: R10 <- data$V4 positionBefore <- match(R10,R10) itemBefore <- R10[c(NA, positionBefore)] R10 <- rev(data$V4)) positionAfter <- match(R10,

我有一个有几列的数据框。每当第V2列的行值小于20时,第V4列中同一行上的字符元素将替换为字符串“sp_nameofOpelement_nameofBottomeElement”

我的代码:

R10 <- data$V4
positionBefore <- match(R10,R10)
itemBefore <- R10[c(NA, positionBefore)]

R10 <- rev(data$V4))
positionAfter <- match(R10, R10)-1
itemAfter <- rev(R10[c(NA, positionAfter)])

cond <- if data$V2 < 20
data$R10[cond] <- sprintf("sp_%s-%s", itemBefore[cond], itemAfter[cond])
检查我的变量:

NROW(itemBefore[cond]) = 200
NROW(itemAfter[cond]) = 199
显然,两个变量是不相等的,我需要防止这个错误

我的解决方案不起作用:

cond <- data$V2 < 20
if (any(itemAfter[cond]==0)){
    data$R10[cond] <- sprintf("sp_%s-%s", itemBefore[cond], "none")}
}else {data$R10[cond] <- sprintf("sp_%s-%s", itemBefore[cond], itemAfter[cond])}
总目(预期结果):


我的问题是数据的最后一行,在这一行下面没有其他行,因此我们有一个类似于:sty 17 tuc sp_carq_的情况?。“?”表示下面没有任何项目。

cond如果太长,您可以发布
dput(数据)
头(数据)
的结果吗?你更有可能通过这种方式得到答案。
cond <- data$V2 < 20
if (any(itemAfter[cond]==0)){
    data$R10[cond] <- sprintf("sp_%s-%s", itemBefore[cond], "none")}
}else {data$R10[cond] <- sprintf("sp_%s-%s", itemBefore[cond], itemAfter[cond])}
V1  V2 V3   V4
str 50  str2    pass
tre 13  stup1   plus
tre 70  vry plus
carq    60  rty plus
sty 17  tuc pass
V1  V2 V3   V4
str 50  str2    pass
tre 13  stup1   sp_str_tre
tre 70  vry plus
carq    60  rty plus
sty 17  tuc sp_carq_?