2013-10-02 143 views
0

对于R,我真的很新,所以对不起,如果我没有完全理解。基于列值的重复排序

我有一个DF数据收集在几个不同的领域,称为STAND。我需要为从1:3运行的数据创建一个序列,但是当涉及到新的STAND号码时,必须重新启动序列。

下面是一些虚拟的数据

STAND TREE_SPECIES DIAMETER 
1 101737 Pine    276 
2 101737 Spruce   98 
3 101737 Spruce  104 
4 101737 Leaf   53 
5 155897 Spruce  82 
6 155897 Spruce  61 
7 155897 Leaf   97 
8 155897 Spruce  89 
9 155897 Spruce  75 
10 202568 Spruce  46 
11 202568 Spruce  56 
12 202568 Pine   204 
13 202568 Spruce  132 
14 202568 Spruce  93 

我希望它看起来像这样:

STAND TREE_SPECIES DIAMETER  SEQ 
1 101737 Pine    276   1 
2 101737 Spruce   98   2 
3 101737 Spruce  104   3 
4 101737 Leaf   53   1 
5 155897 Spruce  82   1 
6 155897 Spruce  61   2 
7 155897 Leaf   97   3 
8 155897 Spruce  89   1 
9 155897 Spruce  75   2 
10 202568 Spruce  46   1 
11 202568 Spruce  56   2 
12 202568 Pine   204   3 
13 202568 Spruce  132   1 
14 202568 Spruce  93   2 

如果是任何帮助,我有90个矗立着一个总的在我的DF 7416行分。

到目前为止,我已经试过:

myDF$SEQ <- seq(1:3) 

但是,只有列表1:3,在整个东风。

非常感谢您的帮助!

+1

Hi和欢迎计算器如你新在SO上,请花些时间阅读[关于Stackoverflow](http://stackoverflow.com/about)和[如何提问](http://meta.stackoverflow.com/help/how-to-ask)。如果您提供[最小,可重现的数据集],您更有可能收到答案(http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610 #5963610)和向我们展示您尝试的解决方案,为什么他们没有工作,以及预期的结果。谢谢! – Henrik

回答

1

试试这个:

df$SEQ <- ave(x = df$STAND, df$STAND, FUN = function(y) rep(1:3, length.out = length(y))) 

或者更短,但具有相同的结果,如果你能与警告消息住,由于1循环:3个序列沿着每个支架的长度 - 长度不属于一定长度为1的倍数:3:

df$SEQ2 <- ave(df$STAND, df$STAND, FUN = function(y) 1:3) 

其结果是:

df 
#  STAND TREE_SPECIES DIAMETER SEQ SEQ2 
# 1 101737   Pine  276 1 1 
# 2 101737  Spruce  98 2 2 
# 3 101737  Spruce  104 3 3 
# 4 101737   Leaf  53 1 1 
# 5 155897  Spruce  82 1 1 
# 6 155897  Spruce  61 2 2 
# 7 155897   Leaf  97 3 3 
# 8 155897  Spruce  89 1 1 
# 9 155897  Spruce  75 2 2 
# 10 202568  Spruce  46 1 1 
# 11 202568  Spruce  56 2 2 
# 12 202568   Pine  204 3 3 
# 13 202568  Spruce  132 1 1 
# 14 202568  Spruce  93 2 2 

avex向量(此处为STAND)拆分为由下一个(未命名)参数(此处为STAND)的级别定义的块。应用于ave中每件的默认功能FUNmean。在这里,我们将该函数更改为“匿名函数”function(y),我们将其定义为rep(1:3, length.out = length(y))。 'y'对应于每件作品。你可以用任何名字取代'y'(例如function(chunk) rep(1:3, length.out = length(chunk))),你会发现很多人经常使用function(x),但我不想在这里使用'x'作为每个部分的名字,因为'x'也被使用如在ave整个向量参数对于每个片,rep licate值1:3至所需长度(length.out),即,每个片的长度:length(y)