Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the nth character within a loop using R [duplicate]

Tags:

loops

r

head

tail

For context, I am writing a code in R that selects out the most common character from a list of strings - determining the most common character in the first position of each string, and so on. To start I am running a loop within a loop to save each character to a list for use later.

I am trying to use the head function to select out each character along the string, which of course is giving me the first character, first two characters, and so on when what I want is the first, second, third, etc. character to be saved to the list.

Here is my code so far:

Store <- list()

for (j in (1:SequenceNumber)){
  SequenceLength <- length(Sequences[[j]])

for (i in (1:SequenceLength)){
  Store[[length(Store)+1]] <- head(Sequences[[j]], n=i)
}
}

So in summary, I am wondering what (probably extremely simple) solution there might be to select the nth element only within a loop using R.

I have tried looking around for a solution, but can only find results selecting out a specified range (for example, the first five results), instead of the nth result.

like image 334
Eeconyn Avatar asked Jan 09 '23 19:01

Eeconyn


1 Answers

To get the Nth letter in a string use substring. For example, the 5th letter in Chicago:

> substring("Chicago", 5, 5)
[1] "a"
like image 105
cory Avatar answered Jan 11 '23 19:01

cory