Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 分析种群随时间的演化_R_Dplyr - Fatal编程技术网

R 分析种群随时间的演化

R 分析种群随时间的演化,r,dplyr,R,Dplyr,每天我都有一个带有ID和一些变量的新csv文件。ID在几天内可能会有所不同。我想获取一天的ID,并跟踪变量随时间的变化 我的目标是创建如下面积图: 例如,我在3月31日获取了所有ID,每天我都与这些ID进行连接,并通过var“Code”创建一个计数组。如果缺少ID(这里的ID是3月31日,而不是D天),他们的代码将变为“NA”,以显示随着时间的推移我“丢失”了多少ID。我希望我足够清楚 下面是我如何计算这幅图的:(我的真实数据像li,而不是data) 库(plyr) 图书馆(dplyr) 您可能

每天我都有一个带有ID和一些变量的新csv文件。ID在几天内可能会有所不同。我想获取一天的ID,并跟踪变量随时间的变化

我的目标是创建如下面积图:

例如,我在3月31日获取了所有ID,每天我都与这些ID进行连接,并通过var“Code”创建一个计数组。如果缺少ID(这里的ID是3月31日,而不是D天),他们的代码将变为“NA”,以显示随着时间的推移我“丢失”了多少ID。我希望我足够清楚

下面是我如何计算这幅图的:(我的真实数据像
li
,而不是
data

库(plyr)
图书馆(dplyr)

您可能希望使用
data.table
rbindlist()
查看的数据<代码>数据。表
按引用操作比基本操作(例如,
rbind()
)更有效,因为它们不会重写整个数据集。我无法重现您的结果。我在count(,,code)中不断得到一个错误
%%>%group\u by(code)%%>%count(code)
的两个实例之后都找不到对象“code”
。为什么要在没有尝试使用data.table的情况下标记它?嗯,我尝试使用dplyr或data.table在数据帧上工作,我尝试的内容不值得显示。所以我刚刚发布了我通过dplyr和taged data.table实现的成果,因为我认为这可能是一个很好的解决方案。无论如何,如果这是一种误用,我会删除标记…不确定如何处理data.frame data.table。这些标记(dplyr/data.table)非常特定于使用这些包的bug、问题或更好的解决方案,而不是那些认为使用该包可能有更好解决方案的问题。但这似乎是一个常见的误解。谢谢你移除标签。
library(plyr)
library(dplyr)

datas <- data.frame(id1 = c("x", "y", "x", "y", "z", "x", "z"), 
                    id2 = c("x2", "y2", "x2", "y2", "z2", "x2", "z2"), 
                    code = c("code1", "code2", "code1", "code2", "code2", "code1", "code2"),
                    var = runif(7),
                    date = do.call(c, mapply(rep, seq(Sys.Date() - 2, Sys.Date(), by = 1), c(2, 3, 2))))

li <- split(datas, datas$date)

dateStart <- Sys.Date() - 2
dateEnd <- Sys.Date()
# A "filter" if I want to start with another date than the date min or end with another date than the max date
li <- li[as.Date(names(li)) >= dateStart & as.Date(names(li)) <= dateEnd]

dfCounts <- ldply(li, function(x) 
  left_join(li[[1]], x, by = c("id1", "id2")) %>% 
    group_by(code.y) %>% 
    count(code = code.y) %>% 
    mutate(freq = n / sum(n), 
           code = ifelse(is.na(code), "NA", code))), 
  .id = "date")

> dfCounts
date code n freq
1 2015-07-04    1 1  0.5
2 2015-07-04    2 1  0.5
3 2015-07-05    1 1  0.5
4 2015-07-05    2 1  0.5
5 2015-07-06    1 1  0.5
6 2015-07-06   NA 1  0.5

dfCounts %>% 
  ggplot(aes(date, freq)) + 
  geom_area(aes(fill = code), position = "stack")
# I have no idea why in this example, nothing is shown in the plot, but it works on my real datas