2015-09-29 20 views
-2

假設我的數據是這樣的如何在模式中標記唯一的事件,因爲這些值在同時發生時是唯一的,而不是在它們分開時發生。

student article.bought 
1  A   pen 
2  B   pencil 
3  V   book 
4  A   pen 
5  A  inkbottle 
6  B   pen 
7  B   pencil 
8  B   pencil 
9  V   book 
10  Z   marker 
11  A  inkbottle 
12  V   book 
13  V   pen 
14  V   book 

我需要的物品獨特的出現可能是像一個不同的專欄,

student article.bought Occurences 
1  A   pen   1 
2  B   pencil   1 
3  V   book   1 
4  A   pen   1 # as A is taking a pen again 
5  A  inkbottle   2 # 'A' changed from pen to ink bottle 
6  B   pen   2 
7  B   pencil   3 # though B took pencil before, this is different as he took a pen in between 
8  B   pencil   3 
9  V   book   1 
10  Z   marker   1 
11  A  inkbottle   2 
12  V   book   1 
13  V   pen   2 
14  V   book   3 
+0

感謝您的快速回復。文章應該是唯一標記的。如果學生拿一篇文章,它應該被標記爲1,下一篇文章爲2等等。如果文章立即重複,數字應該保持不變並且如果在介紹了一些文章之後重複了該文章,那麼該文章應該被視爲另一篇文章 –

+0

,因此,如果您想在一個學生內部從一篇文章轉換到另一篇文章時想增加一個數值,原始排序順序是否有意義?當這個學生以前使用過的產品發生轉變時(但不是在......之前......例如筆書筆),這個數值應該做什麼? – MikeD

+0

是的,只要在一名學生中有一篇文章向另一篇文章過渡,就要增加一個數值。 –

回答

0

在R,我們可以通過尋找差異,diff,每個後續價值的發現學生的選擇更改。當我們獲得該邏輯索引的累計總和cumsum時,我們得到了發生次數的計數。

在第二行中,我們強制將因子變量article.bought設置爲numeric,並使用ave從第一行開始運行函數,以按學生對函數f進行分組。

f <- function(x) cumsum(c(F, diff(x) != 0)) + 1 
df$Occurences <- with(df, ave(as.numeric(article.bought), student, FUN=f)) 
df 
# student article.bought Occurences 
# 1  A   pen   1 
# 2  B   pencil   1 
# 3  V   book   1 
# 4  A   pen   1 
# 5  A  inkbottle   2 
# 6  B   pen   2 
# 7  B   pencil   3 
# 8  B   pencil   3 
# 9  V   book   1 
# 10  Z   marker   1 
# 11  A  inkbottle   2 
# 12  V   book   1 
# 13  V   pen   2 
# 14  V   book   3 
+0

是的!它的工作..非常感謝你..非常有幫助 –

0
  1. 創建附加列[原創排序]和1 枚舉...
  2. 按學生/原始排序順序排列表
  3. enter =IF(A2=A1,IF(B2=B1,D1,D1+1),1)在D2和
  4. 將列d複製到值(複製,粘貼爲...值)
  5. 恢復原來的排序順序

如果這是不是一次性的多,使用相同的策略創建一個VBA腳本

enter image description here

+0

好的一個。謝謝你這麼多。 –

0

一個鏡頭與SAS:

data try00; 
length student article $20; 
infile datalines dlm=' '; 
input student $ article $; 
datalines; 
A pen 
B pencil 
V book 
A pen 
A inkbottle 
B pen 
B pencil 
B pencil 
V book 
Z marker 
A inkbottle 
V book 
V pen 
V book 
; 

data try01; 
set try00; 
pos=_n_; 
run; 

proc sort data=try01 out=try02; by student pos article; run; 

proc sort data=try02 out=stud(keep=student) nodupkey; by student; run; 

data shell; 
length occurrence 8.; 
set try02; 
if _n_>0 then delete; 
run; 

%macro loopstudent(); 

data _null_; set stud end=eof; if eof then call symput("nstu",_n_); run; 


%do i=1 %to &nstu; 
data _null_; set stud; if _n_=&i then call symput("stud&i",student); run; 

data thisstu; 
set try02; 
where student="&&stud&i"; 
dummyart=lag(article); 
retain occurrence 0; 
if dummyart ne article then occurrence=occurrence+1; 
else occurrence=occurrence; 
drop dummyart; 
run; 

proc append base=shell data=thisstu; run; 

%end; 

proc sort data=shell out=final; by pos; run; 

%mend loopstudent; %loopstudent(); 

數據集 「最後的」 有結果。

+0

謝謝你的代碼 –

相關問題