努力使while语句继续迭代R中的每一行
我尝试使用循环来平衡数据行,基于每个行的第一列中的值。下面只是一个示例,我最终希望在更大的数据集中基于列的最大值和最小值运行类似的操作 如果第一列是低于11的数字,我想稍微增加它,并将第二列和第三列减少相应的值。我还想说明是否有任何V1值高于某个级别 我尝试了各种代码,或者收到一条关于length>1的条件的警告消息,或者立即实现break子句。请参阅下面的代码努力使while语句继续迭代R中的每一行,r,while-loop,R,While Loop,我尝试使用循环来平衡数据行,基于每个行的第一列中的值。下面只是一个示例,我最终希望在更大的数据集中基于列的最大值和最小值运行类似的操作 如果第一列是低于11的数字,我想稍微增加它,并将第二列和第三列减少相应的值。我还想说明是否有任何V1值高于某个级别 我尝试了各种代码,或者收到一条关于length>1的条件的警告消息,或者立即实现break子句。请参阅下面的代码 mat <- matrix(data = seq(10, 21, by=1), nrow = 6, ncol =3 ) mat
mat <- matrix(data = seq(10, 21, by=1), nrow = 6, ncol =3 )
mat <- as.data.frame(mat)
continue <- TRUE
while(continue) {
for(i in 1:nrow(mat)) {
if(mat[i,1] > 12) {
mat[i, "V1"] <- "high"
} else if (mat[i,1] < 11) {
mat[i, "V1"] <- mat$V1[i] + 0.1;
mat[i, "V2"] <- mat$V2[i] - 0.03;
mat[i, "V3"] <- mat$V3[i] - 0.07
print(paste("V1", mat$V1))
} else if (mat[i,1] > 11) {
continue <- FALSE
}
}
}
mat这可能适用于您,但在较大的数据集上速度较慢
mat <- matrix(data = seq(10, 21, by=1), nrow = 6, ncol =3 )
mat <- apply(mat,2,as.character)
continue <- TRUE
while(continue) {
mat <- apply(mat,1,function(x){
if(any(grepl("high",x))){
return(x)
}else{
x_ <- as.numeric(x)
if(x_[1] > 12){
x[1] <-"high"
}else if(x_[1] <= 11){
x[1] <- as.character(x_[1] + 0.01)
x[2] <- as.character(x_[2] - 0.03)
x[3] <- as.character(x_[3] - 0.07)
}
return(x)
}
}) %>% t
stop_ <- mat[,1]
stop_[as.numeric(stop_) > 11] <- "high"
if(all(stop_=="high")){
continue <- F
}
}
mat
[,1] [,2] [,3]
[1,] "11.01" "12.97" "2.93"
[2,] "11.01" "16.97" "10.93"
[3,] "12" "18" "12"
[4,] "high" "19" "13"
[5,] "high" "20" "14"
[6,] "high" "21" "15"
mat假设第一列距离11不太远,该代码应该在大型数据集上正常工作。
还可以计算出每行需要多少个循环,并在一个步骤中完成。如果速度是一个潜在的问题,我会改进我的代码来做到这一点
mat <- matrix(data = seq(10, 21, by=1), nrow = 6, ncol =3 )
while(!all(mat[,1] > 11)) {
toolow=mat[,1]<=11
mat[toolow,1] <- mat[toolow,1] + 0.01
mat[toolow,2] <- mat[toolow,2] - 0.03
mat[toolow,3] <- mat[toolow,3] - 0.07
}
## We unfortunately get some floating point error.
mat = round(mat, 3)
mat = apply(mat,2,as.character)
mat[as.numeric(mat[,1])>12,1]="high"
mat
mat 11)){
toolow=mat[,1]谢谢,这非常有效。“all”函数非常有用!带R的键通常可以同时在所有行上编写代码。这有助于提高速度和清晰度。any和all函数对此非常有用。