首页 > 解决方案 > Confused for the "which" in R

问题描述

I am one green hand and confused for following coding when using "which"

> s
  a b
1 1 3
2 2 4
> s[which(s$a>1)][,]
[1] 3 4
> #what I want in fact is to get the dataframe if value a>1 
> s[which(s$a>=1)][,]
  a b
1 1 3
2 2 4
> #no difference for >1 or >=1
> s[which(s$a%in%c(2))][,]
[1] 3 4
> #this way works
> s[which(s$a%in%c(1,2))][,]
  a b
1 1 3
2 2 4
> str(s)
'data.frame':   2 obs. of  2 variables:
 $ a: num  1 2
 $ b: num  3 4

标签: r

解决方案


这是一个简短的解释:如果你这样做,你会得到值 2(一个索引)

which(df$a>1)
[1] 2

现在根据使用的子集的性质,您可以得到行或列。这将返回一列(第 2 列)。

df[which(df$a>1)]
  b
1 3
2 4

这会返回正确的值(我假设这是你想要的)

df[which(df$a>1),]
  a b
2 2 4

笔记::

df<-read.table(text="a b
 1 3
 2 4",header=T)

推荐阅读