r - 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
解决方案
这是一个简短的解释:如果你这样做,你会得到值 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)
推荐阅读
- c# - 用于传输树结构的进程间通信
- markdown - Markdown:强制两个连续的单词在同一行
- python - Python 子进程在脚本中失败:AttributeError:“模块”对象没有属性“Popen”
- python - Scrapy 无法从 URL 下载图像
- java - java.io.NotSerializableException: org.apache.storm.spout.SpoutOutputCollector
- android - AmazFit Bip 手表 - 心率
- java - 为 aws lambda 中的代码生成 swagger 文件
- mysql - 在 MYSQL 中插入期间创建触发器显示错误
- http - 当依赖/下游(如 3rd 方 API)失败时使用什么 HTTP 状态代码?
- kubernetes - kubectl 无法访问远程集群