如何根据另一个变量来查看变量的某个值/类别(大型数据集)

问题描述 投票:0回答:1

我是根据我在 R studio 中遇到的另一个问题来写这个问题的。我有一个非常大的数据集,其中包含鸟类的运动数据 (ACC),每个个体有多个行(每行代表一个时间戳)。 在我的数据集中,我需要查看某个地区有多少人。 这里的问题是,我每个人都有很多行,并且使用表或摘要等简单函数返回分配给该区域的行数。我想要的是使用一个简单的函数来了解属于该领土的个人。

这就是我到目前为止所做的:

  • 我的数据框中有很多行,但只有大约 50 个人(每个人有多行)。
  • 我总共有大约 15 个地区,每一行都有一个地区 ID(重复)。

我尝试过使用表格

table(df$territory_id) %>% sort(decreasing = TRUE) %>% head

这给了我输出:

ter1  ter2  ter3  ter4  ter5  ter6 
275034 207746 232739 165260 162103 259644

这里我有具有区域 ID 的行数。因为我想知道有多少不同的人属于一个领土,所以我将这些领土划分为单独的对象并为此制作了表格:

t <- filter(df, territory == "ter1")

然后:

table(t$individualID)

这给了我想要的输出。但是,我需要对每个地区重复该过程。

我想知道是否有更简单的方法?我只有 15 个区域,但如果有更多区域,则需要花费大量时间来重复该功能。有更简单的方法吗?

数据:

structure(list(tagID = c(5861, 5861, 5861, 5861, 5861, 5861), 
    territory_id = c("GR034", "GR034", "GR034", "GR034", "GR034", 
    "GR034"), timestamp = structure(c(1537266900, 1537267210, 
    1537267501, 1537267800, 1537268101, 1537268413), tzone = "UTC", class = c("POSIXct", 
    "POSIXt"))), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))
r dplyr subset summary
1个回答
0
投票

您的数据看起来相当大,因此虽然您的头脑可以了解数据的样子,但使用起来并不好(因为对于一个位置的一只鸟来说,它似乎有六个时间戳)。所以我创建了自己的,希望仍然相似:

library(tidyverse)
set.seed(0)

df <- data.frame(
    bird_id = rep(1:10, each = 10),
    territory_id = sample(LETTERS[1:10], 100, replace = TRUE),
    timestamp =  ymd_hms("2023-01-01 12:00:00") + sample(1:10000000, 100, replace = TRUE))
> head(df)
  bird_id territory_id           timestamp
1       1            I 2023-03-05 03:57:14
2       1            D 2023-01-01 21:06:37
3       1            G 2023-03-01 07:23:02
4       1            A 2023-02-23 01:09:48
5       1            B 2023-03-29 22:41:45
6       1            G 2023-01-29 03:29:01

因此,虽然我很清楚你想分析你的数据集,但我不确定你具体想做什么。因此,这里有一些您可能想要的东西,以及如何实现它们:

# 1. get the number of birds you have seen at any point in each territory
df |>
  distinct(territory_id, bird_id) |>
  count(territory_id)

# 2. count the number of rows in your dataset for each territory
count(df, territory_id)

# 3. count the number of rows in your dataset for each territory and bird

count(df, territory_id, bird_id)
© www.soinside.com 2019 - 2024. All rights reserved.