We have an input character vector, with each string having two values separated by ':'. The value on the left is a string, whereas the value on the right is an integer.
We want to get a character vector for the value that go before ':'.
We want to get an integer vector for the values that go after ':'.
In addition, we create a combined list, with the values extracted from the input vector. The strsplit function creates a list when it is given a character vector, as well as the split character.
# ex37.R
chr.vec <- c("time:30","pos:45","loc:5")
sep <- strsplit(chr.vec,":")
first.vec <- sapply(sep, function(x) x[1])
second.vec <- as.integer(sapply(sep, function(x) x[2]))
combined.vec <- lapply(sep, function(x) c(x[1],x[2]))
cat("original: ", chr.vec, '\n')
cat("first.vec = ", first.vec,'\n')
cat("second.vec = ", second.vec,'\n')
cat("combined.vec = \n")
print(combined.vec)
# original: time:30 pos:45 loc:5
# first.vec = time pos loc
# second.vec = 30 45 5
# combined.vec =
# [[1]]
# [1] "time" "30"
#
# [[2]]
# [1] "pos" "45"
#
# [[3]]
# [1] "loc" "5"
No comments:
Post a Comment