我正在将数据加载到R中,我想找到与某个日期相关的观察数字。是否有功能/命令可以让我找到日期“2010-09-24”的观测编号,数据中是7?样品中最大重量的观察数如何?在数据示例中,在观察5时它将是53348.我将不胜感激任何帮助。谢谢!
library(zoo)
dat=read.zoo("filelocation",header=T,colClasses=c("Date","numeric"))
obs date weight
1 2010-10-04 52495
2 2010-10-01 53000
3 2010-09-30 52916
4 2010-09-29 52785
5 2010-09-28 53348
6 2010-09-27 52885
7 2010-09-24 52174
8 2010-09-23 51461
9 2010-09-22 51286
10 2010-09-21 50968
11 2010-09-20 49250
数据的结构是这样的:
>dput(head(data))
structure(c(100, 101.01, 110.75, 111.24, 104.96, 104.95, 104.06,
109.08, 113.48, 111.6, 108, 107.95, 95.96, 100.5, 109.05, 103.57,
103.88, 104.66, 100.34, 108.31, 109.4, 104.87, 106, 107.91, 22351900,
11428600, 9137200, 7631300, 4598900, 3551000, 100.34, 108.31,
109.4, 104.87, 106, 107.91, NA, NA, NA, NA, NA, NA), .Dim = 6:7, .Dimnames = list(
NULL, c("weight", "height", "BMI", "Age", "Age2", "Intr",
"Chol")), index = structure(c(12649, 12650, 12653, 12654,
12655, 12656), class = "Date"), class = "zoo")
答案 0 :(得分:4)
zoo类由两个结构组成,索引和核心。您想查询coredata
的一列。必要的是字符矩阵,因为你有字符值。所以记住这一点:
which( coredata(dat)[ ,2] == "2010-09-24")
(您不能在动物园核心中使用日期分类变量作为矩阵。您应该学习如何读取数据,以便将Date列用作索引列。)
dat=zoo(read.table(text="obs date weight
1 2010-10-04 52495
2 2010-10-01 53000
3 2010-09-30 52916
4 2010-09-29 52785
5 2010-09-28 53348
6 2010-09-27 52885
7 2010-09-24 52174
8 2010-09-23 51461
9 2010-09-22 51286
10 2010-09-21 50968
11 2010-09-20 49250",header=T))
> which( coredata(dat)[ ,2] == "2010-09-24")
[1] 7
该对象中唯一的日期值位于索引而不是核心:
which(index(dat) == as.Date("2004-08-24"))
#[1] 4
这说明使用which.max
(在coredata上,但您不需要使用coredata
函数访问,因为[.zoo
将隐式“假设”您感兴趣的内容。)
> which.max(dat[,"weight"])
[1] 4
> dat[ which.max(dat[,"weight"]) , ]
weight height BMI Age Age2 Intr Chol
2004-08-24 111.24 111.6 103.57 104.87 7631300 104.87 NA
答案 1 :(得分:-3)
您可以尝试使用:
which(data == 'foo')
那应该返回索引值。您可以使用以下示例来显示此信息 - 格式似乎是通过复制/粘贴到SO中而混乱,但“汽车”是数据集。
which(cars$dist == 2)
[1] 1