0

我在 R 工作。我有一个数据框,df如下所示:

> str(exp)
'data.frame':   691200 obs. of  19 variables:
 $ groupname: Factor w/ 8 levels "rowA","rowB",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ location : Factor w/ 96 levels "c1","c10","c11",..: 1 2 3 4 12 23 34 45 56 67 ...
 $ starttime: num  0 0 0 0 0 0 0 0 0 0 ...
 $ inadist  : num  0 0.2 0 0.2 0.6 0 0 0 0 0 ...
 $ smldist  : num  0 2.1 0 1.8 1.2 0 0 0 0 3.3 ...
 $ lardist  : num  0 0 0 0 0 0 0 0 0 1.3 ...
 $ fPhase   : Factor w/ 2 levels "Light","Dark": 2 2 2 2 2 2 2 2 2 2 ...
 $ fCycle   : Factor w/ 6 levels "predark","Cycle 1",..: 1 1 1 1 1 1 1 1 1 1 ...

我想添加另一列,timepoint,它给出了它所在starttime的开头的相对值。对于.fCyclestarttime=1801timepoint=1fCycle='Cycle 1'

最好的创作方式是df$timepoint什么?

ETA 玩具数据集:

starttime fCycle timepoint
1         1      1
2         1      2
3         1      3
4         1      4
5         2      1
6         2      2
7         2      3
8         2      4
9         3      1
10        3      2
11        3      3
12        4      1
13        4      2
14        4      3
15        5      1
16        5      2
17        6      1
18        6      2
19        6      3
20        6      4
4

2 回答 2

4

你可以rle结合sequence. 这是一些示例代码。输出是你要找的吗?

require(plyr)

mydf = data.frame(
  starttime = 1:20,
  fCycle    = c(rep(1:3, each = 4), rep(4:5, each = 3), rep(6, 2))
)

# sort data in increasing order of cycle and starttime
mydf = arrange(mydf, fCycle, starttime)

mydf = transform(mydf, timepoint = sequence(rle(fCycle)$lengths))

注意:鉴于在同一个 fCycle 中可能有相同的开始时间,这里有一种替代方法,使用rankddply

# treat same starttimes in an fcycle identically
ddply(mydf, .(fCycle), transform, timepoint = rank(starttime, ties = 'min'))

# treat same starttimes in an fcycle using average
ddply(mydf, .(fCycle), transform, timepoint = rank(starttime, ties = 'average'))
于 2011-08-04T19:01:02.000 回答
2

这是一个解决方案的大纲,因为我不太清楚你在问什么。似乎您正在要求从运行长度编码 (RLE) 派生的东西,它可以通过rle()函数开始。

  1. 输出将rle()给出每次运行的长度(分配 this lengths)。
  2. 可以计算每次运行发生的偏移量(通过cumsum(c(1,lengths)))。
  3. 然后可以rep(重复)足够的次数(即对于运行中的每个项目)。
  4. 对于每个位置 ( 1:n),只需减去运行开始的位置。

编辑:没有必要rep在第 3 步中使用。它可以查找长度。

于 2011-08-04T18:22:24.157 回答