[英]R: What am I doing wrong in this for-loop with an if-else statement?
Sample data:样本数据:
df <- data.frame(apples = c(1, 5, 3),
oranges = c(5, 3, 5))
Problem:问题:
for(i in names(df)){
if(sum(df$i == 5) == 1){
print(paste("There is only 1 occurance of 5 fruit for", i))
} else {
print(paste("There is more than 1 occurance of 5 fruit for", i))
}
}
this gives me这给了我
[1] "There is more than 1 occurance of 5 fruit for apples"
[1] "There is more than 1 occurance of 5 fruit for oranges"
however...然而...
> sum(df$apples == 5)
[1] 1
> sum(df$oranges == 5)
[1] 2
My expected output:我的预期输出:
[1] "There is only 1 occurance of 5 fruit for apples"
[1] "There is more than 1 occurance of 5 fruit for oranges"
I suspect it's some sort of syntax issue, or am I missing something more obvious?我怀疑这是某种语法问题,还是我遗漏了更明显的东西?
You need to use df[[i]]
not df$i
in your loop, otherwise it is finding variable i
in the dataframe.您需要在循环中使用
df[[i]]
而不是df$i
,否则它会在数据框中找到变量i
。 df$i
is NULL. df$i
为 NULL。 sum(NULL == 5)
is 0. You always do that else
bit. sum(NULL == 5)
是 0。你总是else
做。
Instead of summing the columns separately you could use colSums
which is generally much faster.您可以使用
colSums
通常更快,而不是单独对列求和。 The result of a subsequent ifelse
, which has names, can be piped into lapply
to loop over the names (where _
is the placeholder for the piped object).具有名称的后续
ifelse
的结果可以通过管道传输到lapply
以遍历名称(其中_
是管道对象的占位符)。 sprintf
then inserts them at the formal character %s
.然后
sprintf
将它们插入到正式字符%s
处。 Gives a list as result.给出一个列表作为结果。
ifelse(colSums(df == 5) > 1, 'only', 'more than') |>
lapply(X=_, sprintf, fmt='There is %s 1 occurance of 5 fruits for')
# $apples
# [1] "There is more than 1 occurance of 5 fruits for"
#
# $oranges
# [1] "There is only 1 occurance of 5 fruits for"
R >= 4.2 needed.需要 R >= 4.2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.