Home > Blockchain >  Is it possible to access characters in a string in R without using strsplit and only basic R functio
Is it possible to access characters in a string in R without using strsplit and only basic R functio

Time:08-10

Suppose I had the character vector in R:

x <- "hello world"

and I wanted to access each element individually. I know that strsplit in R can do this, but was wondering if there was a way to access elements without relying on such a function?

CodePudding user response:

Are you looking for an alternative like:

scan(text = x, what = "")
#[1] "hello" "world"

or (substr and substring have been mentioned in comments):

## not `substr`
substring(x, 1:nchar(x), 1:nchar(x))
#[1] "h" "e" "l" "l" "o" " " "w" "o" "r" "l" "d"

intToUtf8(utf8ToInt(x), TRUE)
#[1] "h" "e" "l" "l" "o" " " "w" "o" "r" "l" "d"

Of course, you already know

strsplit(x, "")[[1]]
#[1] "h" "e" "l" "l" "o" " " "w" "o" "r" "l" "d"

CodePudding user response:

If you are looking for an alternative, you can use the regular expression. It's a powerful tool that is supported by R.

library(tidyverse)
str_extract(x, "\\w ") #you ask to extract each word separated by a space. It includes words or numbers.
#the first \ is to indicate you are using regex.

hope this will help

  •  Tags:  
  • r
  • Related