2014-11-01 12 views

回答

9

這裏有幾個想法

scan(text="1,2,3,", sep=",", quiet=TRUE) 
#[1] 1 2 3 NA 

unlist(read.csv(text="1,2,3,", header=FALSE), use.names=FALSE) 
#[1] 1 2 3 NA 

這些都返回整數向量。你可以用as.character圍繞其中任何讓你在問題中準確顯示輸出:

as.character(scan(text="1,2,3,", sep=",", quiet=TRUE)) 
#[1] "1" "2" "3" NA 

或者,你可以在read.csv指定scanwhat="character",或colClasses="character"的輸出略有不同

scan(text="1,2,3,", sep=",", quiet=TRUE, what="character") 
#[1] "1" "2" "3" "" 

unlist(read.csv(text="1,2,3,", header=FALSE, colClasses="character"), use.names=FALSE) 
#[1] "1" "2" "3" "" 

您還可以指定na.strings=""以及colClasses="character"

unlist(read.csv(text="1,2,3,", header=FALSE, colClasses="character", na.strings=""), 
     use.names=FALSE) 
#[1] "1" "2" "3" NA 
6

哈德利的stringi(以前stringr)庫的基本字符串函數一個巨大的進步(全矢量,一致的功能接口):

require(stringr) 
str_split("1,2,3,", ",") 

[1] "1" "2" "3" "" 

as.integer(unlist(str_split("1,2,3,", ","))) 
[1] 1 2 3 NA 
+3

'stringr'是緩慢的,你應該使用'stringi' :) – 2015-04-21 00:52:34

+3

@silvaran你是完全正確的,我在寫完這些之後才意識到'stringi'。 (如何在R上保持最新的最佳包裝?) – smci 2015-04-21 01:01:04

3

使用stringi包:

require(stringi) 
> stri_split_fixed("1,2,3,",",") 
[[1]] 
[1] "1" "2" "3" "" 
## you can directly specify if you want to omit this empty elements 
> stri_split_fixed("1,2,3,",",",omit_empty = TRUE) 
[[1]] 
[1] "1" "2" "3" 
相關問題