Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从数据帧中选择在For循环R中满足if条件的元素_R_If Statement_For Loop - Fatal编程技术网

从数据帧中选择在For循环R中满足if条件的元素

从数据帧中选择在For循环R中满足if条件的元素,r,if-statement,for-loop,R,If Statement,For Loop,我正在处理函数中的数据帧,我的语法有一个问题。这是我正在使用的框架: c id nobs 1 1 117 2 2 1041 3 3 243 4 4 474 5 5 402 6 6 228 7 7 442 8 8 192 9 9 275 10 10 148 这就是我正在使用的代码 threshold=250 c for (i in c[1]){ if(threshold > any(c[i,2])){ p

我正在处理函数中的数据帧,我的语法有一个问题。这是我正在使用的框架:

c
   id nobs
1   1  117
2   2 1041
3   3  243
4   4  474
5   5  402
6   6  228
7   7  442
8   8  192
9   9  275
10 10  148
这就是我正在使用的代码

threshold=250
c
for (i in c[1]){ 
    if(threshold > any(c[i,2])){
        print(c[i,1])
    }
}
我想要得到的是数据帧的第一个元素是满足条件,但我得到的结果是: [1] 1 2 3 4 5 6 7 8 9 10. 它只需要是:1 3 6 8 10

任何帮助都将不胜感激。提前感谢。

不确定:

subset(c, nobs > threshold)
#df is your dataframe
备选案文1:

 with(df,ifelse(nobs<250,lag(id,1),NA))
     [1]  1 NA  3 NA NA  6 NA  8 NA 10

with(df,ifelse(nobs让我们调用data.frame
x
以避免函数名
c
之间的冲突

按照您的语法,它应该是:

for (i in seq_len(nrow(x))){ 
    if(threshold > x[i,2]){
        print(x[i,1])
    }
}
或者简单地说

x[x[,2] < threshold, 1]
x[x[,2]<阈值,1]
使用
哪个

c[which(c$nobs<250),1]

c[which](c$nobs
c
是一个函数。用其他名称命名对象可能更好。可能重复您为什么需要
which
?是的,但当您说
使用which
,这可能意味着它是必要的。这一个确实做了我想要的,非常感谢!除此之外,请您向我解释一下di使用“for(i in c[1]){”(mine)和使用“for(i in seq_len(nrow(x)){”?@Frank
i in x[1]
在第1列的元素上循环,而在seq_len(nrow(x))中使用
i
在行的索引上循环。如果第一列实际上是行索引,就像您的情况一样,没有区别。初始代码的主要问题是使用
any
any
返回
TRUE
对于任何非
FALSE
/
0
/
NULL(或其他空)
R对象。因此,在您的示例中,
threshold>any(x[i,2])
始终是
TRUE
c[which(c$nobs<250),1]