2015-05-21 30 views
-3

在「計數」變量,我想獲得的次數的函數調用中的R如何找到次數的函數被調用R中

FUN=function(x){ 

    spaces=Category=0 
    k=50-nchar(levels(x)) 
    for (z in 1:length(levels(x))) 
    { 
    spaces[z]=paste(replicate(k[z]," "), collapse="") 
    Category[z]=paste(levels(x)[z],spaces[z],sep="") 
    } 
    df=as.data.frame.matrix(table(x,Sentiment)) 
    attach(df) 
    tot=d+i+s; 
    d_percent=d/tot 
    i_percent=i/tot 
    s_percent=s/tot 
    HSI=(round(100+(i_percent-d_percent)*(1-s_percent)*100)) 
    Weightage=(round(tot*100/sum(d+i+s),1)) 
    HSI_Final=cbind(count,Category,HSI,Weightage) 

    return(HSI_Final) 
} 

回答

3

你可以做這樣的事情

FUN <- local({count=1; function(x){ 
    HSI_Final=count 
    count <<- count + 1 
    return(HSI_Final) 
}}) 

FUN(1) 
# [1] 1 
FUN(1) 
# [1] 2 
FUN(1) 
# [1] 3 
FUN(1) 
# [1] 4 

在這裏,您創建包含計數變量,你可以在函數內部增加局部環境