R 提取特定元素的因子上的迭代
所以我看了和,似乎找不到一个循环或迭代因子的好例子(或者是他们的其他/更好的方法?)。我有一个数据帧,我有:R 提取特定元素的因子上的迭代,r,R,所以我看了和,似乎找不到一个循环或迭代因子的好例子(或者是他们的其他/更好的方法?)。我有一个数据帧,我有: > head(frame) x1 x2 DateTime 1 100 5 2010-06-01 05:32:46 2 105 3 2010-06-01 05:32:23 3 47 20 2010-06-01 05:32:34 4 56 6 2010-06-01 05:33:16 5 98 11 2
> head(frame)
x1 x2 DateTime
1 100 5 2010-06-01 05:32:46
2 105 3 2010-06-01 05:32:23
3 47 20 2010-06-01 05:32:34
4 56 6 2010-06-01 05:33:16
5 98 11 2010-06-01 05:54:12
6 84 9 2010-06-01 05:54:05
我可以创建一个基于时间的因子,比如:
fact我不确定你所说的“提取”第n个元素是什么意思(也就是说,你想要它在同一个对象中,一个新对象中,你想要和原始对象一样长的东西吗,等等)
我会使用ave
,因为它对因子组起作用。请注意,这假设您的data.frame是按frame$DateTime
排序的
frame <- structure(list(
x1 = c(100L, 105L, 47L, 56L, 98L, 84L),
x2 = c(5L, 3L, 20L, 6L, 11L, 9L),
DateTime = structure(c(1275388366, 1275388343, 1275388354, 1275388396,
1275389652, 1275389645), class = c("POSIXct", "POSIXt"), tzone = ""),
fact = structure(c(1L, 1L, 1L, 1L, 1L, 1L),
.Label = "2010-06-01 05:00:00", class = "factor")),
.Names = c("x1", "x2", "DateTime", "fact"),
row.names = c(NA, -6L), class = "data.frame")
transform(frame, firstx2=ave(x2, fact, FUN=function(x) x[1]),
lastx2 =ave(x2, fact, FUN=function(x) x[length(x)]))
# These lines do the same as the `transform` line(s)
frame$firstx2 <- ave(frame$x2, frame$fact, FUN=function(x) x[1])
frame$lastx2 <- ave(frame$x2, frame$fact, FUN=function(x) x[length(x)])
frame谢谢你的帮助,如果我不清楚,我道歉。是的,frame$DateTime已排序,我想我正在尝试将第n个元素提取到一个对象中,然后我可以在类似于boxplot(frame$x2~fact)
的覆盖图上绘制它,在这里我希望显式地看到第一个或最后一个或第n个元素。也许我做错了什么,但试图运行此代码时,我遇到了一个错误“eval(expr,envir,enclose)中的错误:找不到对象‘firstx2’。有什么想法吗?@Bob:可能是你如何创建了frame
。我在回答中添加了一个frame
示例。谢谢,我有点不清楚转换位的作用。内置的R-lang帮助在这里不是很有用,它说“转换是一个通用函数,至少目前它只对数据帧有用。”为什么您的解决方案需要它?@Bob:transform
只是一条语法捷径。我添加了一些行,可以做同样的事情。
frame <- structure(list(
x1 = c(100L, 105L, 47L, 56L, 98L, 84L),
x2 = c(5L, 3L, 20L, 6L, 11L, 9L),
DateTime = structure(c(1275388366, 1275388343, 1275388354, 1275388396,
1275389652, 1275389645), class = c("POSIXct", "POSIXt"), tzone = ""),
fact = structure(c(1L, 1L, 1L, 1L, 1L, 1L),
.Label = "2010-06-01 05:00:00", class = "factor")),
.Names = c("x1", "x2", "DateTime", "fact"),
row.names = c(NA, -6L), class = "data.frame")
transform(frame, firstx2=ave(x2, fact, FUN=function(x) x[1]),
lastx2 =ave(x2, fact, FUN=function(x) x[length(x)]))
# These lines do the same as the `transform` line(s)
frame$firstx2 <- ave(frame$x2, frame$fact, FUN=function(x) x[1])
frame$lastx2 <- ave(frame$x2, frame$fact, FUN=function(x) x[length(x)])