R Language
Stringmanipulatie met stringi-pakket
Zoeken…
Opmerkingen
Om het pakket te installeren, voer je eenvoudig uit:
install.packages("stringi")
om het te laden:
require("stringi")
Tel patroon in string
Met vast patroon
stri_count_fixed("babab", "b")
# [1] 3
stri_count_fixed("babab", "ba")
# [1] 2
stri_count_fixed("babab", "bab")
# [1] 1
native:
length(gregexpr("b","babab")[[1]])
# [1] 3
length(gregexpr("ba","babab")[[1]])
# [1] 2
length(gregexpr("bab","babab")[[1]])
# [1] 1
functie wordt gevectoriseerd over tekenreeks en patroon:
stri_count_fixed("babab", c("b","ba"))
# [1] 3 2
stri_count_fixed(c("babab","bbb","bca","abc"), c("b","ba"))
# [1] 3 0 1 0
Een basis R-oplossing :
sapply(c("b","ba"),function(x)length(gregexpr(x,"babab")[[1]]))
# b ba
# 3 2
Met regex
Eerste voorbeeld - zoek a
en een willekeurig karakter erna
Tweede voorbeeld - zoek a
en elk cijfer erna
stri_count_regex("a1 b2 a3 b4 aa", "a.")
# [1] 3
stri_count_regex("a1 b2 a3 b4 aa", "a\\d")
# [1] 2
Tekenreeksen dupliceren
stri_dup("abc",3)
# [1] "abcabcabc"
Een basis R-oplossing die hetzelfde doet, ziet er als volgt uit:
paste0(rep("abc",3),collapse = "")
# [1] "abcabcabc"
Plak vectoren
stri_paste(LETTERS,"-", 1:13)
# [1] "A-1" "B-2" "C-3" "D-4" "E-5" "F-6" "G-7" "H-8" "I-9" "J-10" "K-11" "L-12" "M-13"
# [14] "N-1" "O-2" "P-3" "Q-4" "R-5" "S-6" "T-7" "U-8" "V-9" "W-10" "X-11" "Y-12" "Z-13"
Natuurlijk kunnen we dit in R doen via:
> paste(LETTERS,1:13,sep="-")
#[1] "A-1" "B-2" "C-3" "D-4" "E-5" "F-6" "G-7" "H-8" "I-9" "J-10" "K-11" "L-12" "M-13"
#[14] "N-1" "O-2" "P-3" "Q-4" "R-5" "S-6" "T-7" "U-8" "V-9" "W-10" "X-11" "Y-12" "Z-13"
Tekst splitsen door een vast patroon
Splitsen van vector van teksten met behulp van één patroon:
stri_split_fixed(c("To be or not to be.", "This is very short sentence.")," ")
# [[1]]
# [1] "To" "be" "or" "not" "to" "be."
#
# [[2]]
# [1] "This" "is" "very" "short" "sentence."
Splits één tekst met veel patronen:
stri_split_fixed("Apples, oranges and pineaplles.",c(" ", ",", "s"))
# [[1]]
# [1] "Apples," "oranges" "and" "pineaplles."
#
# [[2]]
# [1] "Apples" " oranges and pineaplles."
#
# [[3]]
# [1] "Apple" ", orange" " and pineaplle" "."
Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow