R語言strsplit函數用法深入詳解

1、R語言strsplit用於分割字符串

創建測試數據

> test <- "aa bb cc dd ee ff" ##創建測試數據
> test
[1] "aa bb cc dd ee ff"
> class(test) ## 測試數據為字符
[1] "character"

2、按照指定分隔符拆分字符串

> a <- strsplit(test,split = " ") ##制動分隔符為空格進行拆分數據
> a
[[1]]
[1] "aa" "bb" "cc" "dd" "ee" "ff"

> class(a) ## 分割後的數據類型為列表
[1] "list"
> b <- strsplit(test,split = "") ## 分隔符設為空,則拆分每一個字符
> b
[[1]]
 [1] "a" "a" " " "b" "b" " " "c" "c" " " "d" "d" " " "e" "e" " " "f"
[17] "f"
> test <- "aa,bb,cc,dd,ee!ff!GG" ##重新創建測試數據
> strsplit(test,split = ",") ##指定分隔符為","進行拆分
[[1]]
[1] "aa"    "bb"    "cc"    "dd"    "ee!ff!GG"

> strsplit(test,split = "!") ##指定分隔符為"!"進行拆分
[[1]]
[1] "aa,bb,cc,dd,ee" "ff"       "GG"
> test <- "aa,bb,cc,dd,ee!ff!GG" ##重新創建測試數據
> strsplit(test,split = ",") ##指定分隔符為","進行拆分
[[1]]
[1] "aa"    "bb"    "cc"    "dd"    "ee!ff!GG"

> strsplit(test,split = "!") ##指定分隔符為"!"進行拆分
[[1]]
[1] "aa,bb,cc,dd,ee" "ff"       "GG"
> test <- "aa.bb.cc.dd.ee"   ##同上
> strsplit(test,split = ".")
[[1]]
 [1] "" "" "" "" "" "" "" "" "" "" "" "" "" ""

> strsplit(test,split = ".",fixed = T)
[[1]]
[1] "aa" "bb" "cc" "dd" "ee"

3、指定輸出結果為向量

> test <- "aa,bb,cc,dd,ee" ##生產測試數據
> a <- strsplit(test,split = ",") 
> a
[[1]]
[1] "aa" "bb" "cc" "dd" "ee"

> class(a)
[1] "list"
> b <- unlist(strsplit(test,split = ",")) ## 加unlist函數
> b
[1] "aa" "bb" "cc" "dd" "ee"
> class(b)  
[1] "character"

到此這篇關於R語言strsplit函數用法深入詳解的文章就介紹到這瞭,更多相關R語言strsplit函數內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: