2017-03-09 65 views
0

我遇到了包含標點符號的列名稱問題。 我診斷問題如下:標點符號中的標點符號被替換爲..X

file <- "./spam.data.txt" 
columnNames <- c('word_freq_make',  
       'word_freq_address',    
       ...   
       'word_freq_table',   
       'word_freq_conference', 
       'char_freq_;',    
       'char_freq_(',    
       'char_freq_[',    
       'char_freq_!',    
       'char_freq_$',    
       'char_freq_#',    
       'capital_run_length_average', 
        ...) 
spamd <- read.table(file, sep = "" , header = F, stringsAsFactors= F, 
        col.names = columnNames) 

# First look 
spamd$word_freq_85   # [1] 0 0 0 0 0 0 0 0 1 0 1 ... 
spamd$char_freq_;   # NULL 
colnames(spamd) 

colnames()輸出是:

[1] "word_freq_make"    "word_freq_address"  ...   


[46] "word_freq_table"   "word_freq_conference"  "char_freq_."    "char_freq_..1"    
[51] "char_freq_..2"    "char_freq_..3"    "char_freq_..4"    "char_freq_..5"    "capital_run_length_average" 

也就是說,在列名的標點符號被換成「..1" ,」 .. 2「,」。3「,...

爲什麼這麼好嗎?

編輯FOLLOWING AKRUN的回答是:

有:

spamd <- read.table(file, sep = "" , header = F, stringsAsFactors= F, 
        col.names = columnNames, check.names = FALSE) 

,而不是解決了重命名問題。也就是說,現在colnames()產生:

[41] "word_freq_cs"    "word_freq_meeting"   "word_freq_original"   "word_freq_project"   "word_freq_re"    
[46] "word_freq_edu"    "word_freq_table"   "word_freq_conference"  "char_freq_;"    "char_freq_("    
[51] "char_freq_["    "char_freq_!"    "char_freq_$" 

但如果我嘗試spamd$char_freq_X其中X是任何標點符號我仍然得到NULL。那麼,如何訪問這些列呢?

感謝

+5

RTFM'?read.table'和'?make.names' –

+0

我不明白你在說什麼SRY。我是R新手。 – hartmut

+0

我只是說這是記錄的行爲,你可以通過查看功能文檔自己閱讀。這可以通過在你的R控制檯中輸入一個排隊標記(?),然後輸入函數名稱來實現。 –

回答

1

我們需要使用check.names=FALSE

spamd <- read.table(file, sep = "" , header = F, stringsAsFactors= F, 
       col.names = columnNames, check.names = FALSE) 
+0

非常感謝。這解決了重命名問題。但是,正如編輯中所解釋的,我仍然無法訪問名稱中帶有標點符號的列。你能告訴我更多嗎? – hartmut

+2

@hartmut如果你使用'$',例如'spamd $''char_freq_X'''進行提取,你可以使用反引號來訪問這些列(只使用一個反引號 - 忘記了如何在註釋中指定它 – akrun