【问题标题】:visit number by data by within factor group?按因子组内的数据访问次数?
【发布时间】:2012-02-27 13:55:09
【问题描述】:

万事如意,

我在 R 中工作。很抱歉这个非常基本的问题,但我有点卡住了。 我有一个存在/不存在点计数数据的数据集,其中包含计数日期和站点编号(见下文)。我想最终创建一个 data.frame,按网格单元格编号整理所有计数,并将每次访问站点作为新访问(见下文)。我无法弄清楚如何做到这一点,所以我想我会采取更简单的路线并制作一个列,为每条记录提供访问编号。因此,该列将按每个站点组内的访问日期为每条记录提供一个编号(见下文)。我也不知道该怎么做! 任何帮助都会很棒,在此先感谢您。

亲切的问候, 亚当

我有这个:

Site    date
1   12/01/2000
1   24/02/2000
1   13/08/2001
2   14/01/2000
2   21/01/2002
3   1/01/1999
3   21/04/2000

最终想要这个:

Site           vist1              v2                 v3
1              12/01/2000         24/02/2000         13/08/2001
2              14/01/2000         21/01/2002         na
3              01/01/1999         21/04/2000         na

但这会很好:

Site   date        visit
1      12/01/2000  1
1      24/02/2000  2
1      13/08/2001  3
2      14/01/2000  1
2      21/01/2002  2
3      01/01/1999  1
3      21/04/2000  2

【问题讨论】:

  • Adam:可用的示例数据对我们有很大帮助。如果你已经加载了这些,你能给我们一个简短的子集吗? test_data=head(data); dput(data); 然后粘贴来自 dput 的结果。谢谢。
  • 另请注意,在编辑窗口中 {} 将保留代码/数据的格式。

标签: r sorting date cumulative-sum


【解决方案1】:

基本上,您希望将数据从长格式重塑为宽格式,并在一行中重复来自Site 的观察。基本 R 函数 reshape() 就是为这个任务而设计的。

唯一的(轻微的)复杂性是您首先需要添加一个列(我在这里称之为obsNum),用于标识Site 中的第一个、第二个、第三个等观察。通过设置timevar = "obsNum",您可以让reshape() 知道您要将date 的每个值放入哪一列。

df <- read.table(text = "Site date
1 12/01/2000
1 24/02/2000
1 13/08/2001
2 14/01/2000
2 21/01/2002
3 1/01/1999
3 21/04/2000", header=T, stringsAsFactors=FALSE)

df$obsNum <- unlist(sapply(rle(df$Site)$lengths, seq))
reshape(df, idvar="Site", timevar="obsNum", direction="wide")

#   Site     date.1     date.2     date.3
# 1    1 12/01/2000 24/02/2000 13/08/2001
# 4    2 14/01/2000 21/01/2002       <NA>
# 6    3  1/01/1999 21/04/2000       <NA>

【讨论】:

  • 谢谢乔希,这很管用!我一定要更深入地检查这些功能,它们真的很有用。问候,亚当
【解决方案2】:

这是ddplydcast 的另一种解决方案。

library(reshape2)
# Convert the date column into actual dates
df$date <- as.Date(df$date, format="%d/%m/%Y")
# Ensure that the data.frame is sorted
df <- df[ order(df$site, df$date), ]

# Number the visits for each site
df$visit <- 1
d <- ddply(df, "Site", transform, visit=cumsum(visit))

# Convert to a wide format
# (Since dcast forgets the Date type, convert it to strings
# before and back to dates after.)
d$date <- as.character(d$date)
d <- dcast(d, Site ~ visit, value.var="date")
d[,-1] <- lapply(d[,-1], as.Date)
d

【讨论】:

    【解决方案3】:

    这是使用 plyrreshape2 的解决方案的另一种看法。

    require(plyr); require(reshape2); require(lubridate)
    df <- ddply(df, .(Site), transform, visit = rank(dmy(date)))
    dcast(df, Site ~ visit, value.var = 'date')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多