繁体   English   中英

在for循环中子集唯一值

[英]Subsetting unique values within for loop

我试图计算鲨鱼在特定深度花费的时间比例。

我的数据集是这样的:

    deployID depth         datetime       date
   1        A  66.5 18/03/2018 00:00 18/03/2018
   2        A  55.0 18/03/2018 00:02 18/03/2018
   3        A  28.5 18/03/2018 00:05 18/03/2018
   4        A  23.5 18/03/2018 00:07 19/03/2018
   5        A  48.5 18/03/2018 00:10 19/03/2018
   6        A  53.5 18/03/2018 00:12 19/03/2018

但是df1$date一直运行到26/6/2018。 每天有576个观测值,每2.5分钟一个。

我写了一个简单的函数来计算给定日期的比例:

pct.day <- function(a.depth) {
  part.day <- length(a.depth$datetime) / length(sharkA$datetime)
  return(part.day)
}

和一个for循环,我希望能在df1列出的每一天计算出来。

uniq.day = unique(df1$date)
prop_day = list()
for(i in 1:length(uniq.day)){
  day =  subset(df1, date == [[i]])
  sharkA = subset(day, deployID=="A")
  a = subset(sharkA, depth<70 & depth >30)
  prop_day[[i]] <- with(day, pct.day(a))
  m <- data.frame(unlist(prop_day))
}

但是,我遇到了一些错误。 首先,当我运行for循环时,我收到Error: unexpected '}' in "}" 我不确定我是否适当地将每一天都分组

for(i in 1:length(uniq.day)){
  day =  subset(df1, date == [[i]])
}

我希望以m为单位输出18/3/2018和19/3/2018的函数结果,但我不知道我在哪里出错了。

不是使用循环并执行多个子集化选项,而是有更好的R选项,例如lapplysplit函数。

另一个更快的选择是使用dplyr包。 这个包对于这些类型的问题非常方便。 这是一个可能的单线解决方案:

df<-structure(list(deployID = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "A", class = "factor"), 
    depth = c(66.5, 55, 28.5, 23.5, 48.5, 53.5), datetime = c("18/03/2018 00:00", 
    "18/03/2018 00:02", "18/03/2018 00:05", "18/03/2018 00:07", 
    "18/03/2018 00:10", "18/03/2018 00:12"), date = structure(c(1L, 
    1L, 1L, 2L, 2L, 2L), .Label = c("18/03/2018", "19/03/2018"
    ), class = "factor")), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

library(dplyr)
df %>% group_by(deployID, date) %>% summarize(targetdepth=sum(depth<70 & depth>30 ), total=n(), targetdepth/total)

 #deployID date       targetdepth total `targetdepth/total`
 #<fct>    <fct>            <int> <int>               <dbl>
 #A        18/03/2018           2     3               0.667
 #A        19/03/2018           2     3               0.667

这里group_by函数通过day和deployID执行子集化,然后计算<70和> 30的个案数并除以每个子集中的个案总数。

这也比使用循环快得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM