2017-08-19 96 views
0

我想讀R中一個CSV文件並找到文件的列特定的模式,並計算出現了多少次gregexpr的額外信息。以下是代碼:刪除R中

dataframe <- read.csv("path-analysis-2003-a.csv", header = TRUE, stringsAsFactors=FALSE) 

for(i in 1:nrow(dataframe)) 
{ 
    counter <- gregexpr("-",dataframe$Path[i], fixed = TRUE, useBytes = TRUE) 
    print(length(counter)) 

} 

但是,輸出顯示每行的長度爲1。當調試代碼我發現這個輸出:

[[1]] 
[1] 10 19 28 41 43 44 45 46 50 60 67 
attr(,"match.length") 
[1] 1 1 1 1 1 1 1 1 1 1 1 
attr(,"useBytes") 
[1] TRUE 

輸出(其中,位置是給定的)的第一行是有用,因爲我可以從那裏計算的發生。然而,問題是我不知道如何擺脫其他輸出信息。有什麼建議嗎?

+0

'屬性(計數器[[1]])< - NULL',或更簡單地'C(計數器[[1]])' –

+0

感謝您的。你能解釋它是如何工作的嗎? – user2293224

+0

它在'help(gregexpr)'和'help(attributes)'中解釋過。 –

回答

1

以下是您可以遵循的示例。我已經添加了對代碼的評論以使其具有自我解釋性。該示例顯示在包含4個句子的數據框中搜索單詞stop。

# some data for the demo 
text <- c("Because I could not stop for Death -", 
"He kindly stopped for me -", 
"The Carriage held but just Ourselves -", 
"and Immortality") 
# populate sample dataframe 
df_sample <- data.frame(id=1:4, sentence=text) 
# apply gregexpr, note the function is vectorized no need of loop 
result <- gregexpr("stop", df_sample$sentence) 
# unlist result to obtain the indices 
final <- unlist(result) 
# print results 
final