I was browsing some answer concerning strsplit
in R. Example text:
fileName <- c("hello.w-rp-al",
"how.nez-r",
"do.qs-sdz",
"you.d-aerd",
"do.dse-e")
I wanted to get the first element of the created list and thought I could use something such as
fileNameSplit <- strsplit(fileName, "[.]")
node_1 <- fileNameSplit[0]
node_2 <- fileNameSplit[1]
But that didn't work.
Then I found this answer that suggests using sapply
with [
. This does work.
d <- data.frame(fileName)
fileNameSplit <- strsplit(d$fileName, "[.]")
d$node_1 <- sapply(fileNameSplit, "[", 1)
d$node_2 <- sapply(fileNameSplit, "[", 2)
However, I'm trying to figure out why. What exactly is happening, and what does [
have to do with anything? It's semantically confusing in my opinion.