Home > Blockchain >  Why is R only performing a test in the last iteration of a `for` loop?
Why is R only performing a test in the last iteration of a `for` loop?

Time:09-25

I'm trying to learn R better.

I'm trying to split a string, and then run tests on each letter in that string.

I've come up with this:

str <- 'AB'
strs <- strsplit(str, '')
for (letter in strs) {
    writeLines(letter)
    print(identical('A', letter))
}

this outputs:

A
B
[1] FALSE

that is, the identical test was not done, or at least, not printed, for the first letter in strs

How can I get a test to be done on each letter while iterating through a list of strings?

CodePudding user response:

It is because we didn't get inside the list element

for (letter in strs[[1]]) {print(letter);print(identical('A', letter))}
[1] "A"
[1] TRUE
[1] "B"
[1] FALSE

Check the difference in the structure

> str(strs)
List of 1
 $ : chr [1:2] "A" "B"
> str(strs[[1]])
 chr [1:2] "A" "B"
  •  Tags:  
  • r
  • Related