I want to check where the characters in sentence
is placed in alphabet_S
.
I used match function but outcome is NA
. Why is this happening?
sentence<-c("soccer is difficult")
sentence<-tolower(sentence)
sentence2<-strsplit(sentence, "")
alphabet_S<-c("a","b","c","d","e","f","g","h","i","j",
"k","l","m","n","o","p","q","r","s","t",
"u","v","w","x","y","z","next")
match(sentence2,alphabet_S)
CodePudding user response:
We need to extract the list
element with [[
(or unlist
if there are more than one elements in the list). The strsplit
splits and returns a list
match(sentence2[[1]], alphabet_S)
-output
[1] 19 15 3 3 5 18 NA 9 19 NA 4 9 6 6 9 3 21 12 20
Checking the str
ucture gives
> str(sentence2)
List of 1
$ : chr [1:19] "s" "o" "c" "c" ...
CodePudding user response:
If you also want to cycle through larger lists with n entries you can use sapply
sapply(sentence2, match, alphabet_S)
[,1]
[1,] 19
[2,] 15
[3,] 3
[4,] 3
[5,] 5
[6,] 18
[7,] NA
[8,] 9
[9,] 19
[10,] NA
[11,] 4
[12,] 9
[13,] 6
[14,] 6
[15,] 9
[16,] 3
[17,] 21
[18,] 12
[19,] 20