R if if with for循环 [英] R if else with for loop
本文介绍了R if if with for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算比率(A / B = C)。然后我想为比率分配一个标签。如果比率等于0,则标签变为0。如果小于1标签的值为1。最后比率大于1标签得到2。
I would like to calculate a ratio (A / B = C). Then I want to assign a label for ratio. If the ratio equals 0 label gets "0". If value less than 1 label gets "1". Lastly ratio is greater than 1 label gets "2".
以下是示例数据:
A B C
1 0 171.06 0.0000000
2 1 2 0.5
3 0 120.84 360.00000
4 0 308.07 0.0000000
5 0 243.06 0.0000000
6 0 876.015 0.0000000
以下是循环函数:
targets <- function(data)
{
label_df <- data[,c("A", "B")]
label_df[is.na(label_df)] <- 0
label_df["C"] <- (label_df["A"] / label_df["B"])
for(i in 1:nrow(label_df))
{
if(label_df$C == 0){label_df[i,"C"] <- 0}
else if(label_df$C < 1){label_df[i,"C"] <- 1}
else {label_df[i,"C"] <- 2}
}
return(as.data.frame(label_df))
}
这是结果。它显示所有标签0.
And here is the result. It shows all labels 0.
lab <- target(data)
head(lab)
A B C label
1 0 171.06 0.0000000 0
2 1 2 0.5 0
3 0 120.84 360.00000 0
4 0 308.07 0.0000000 0
5 0 243.06 0.0000000 0
6 0 876.015 0.0000000 0
我用table()函数检查结果吧只显示标签0的所有数据。没有1或2个标签。我无法弄清楚问题出在哪里。有什么想法?
I check the result with table() function and it just shows all data for label 0. There are no 1 or 2 labels. I couldn't figure out where the problem is. Any idea?
推荐答案
我们可以用 cut
We can do this with cut
df1$label <- cut(df1$C, breaks = c(-Inf,0, 1, Inf), labels = c(0, 1, 2))
或者 findInterval
findInterval(df1$C, c(0, 1, Inf), left.open = TRUE)
这篇关于R if if with for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文