I am trying to extend the answer from Find string in data.frame and Find multiple strings in entire dataframe.
How can I use the results of coordinations to extract the corresponding elements of the data.frame? Here, the results mean the ones from which()
with arr.ind = TRUE
or sapply()
mat = as.data.frame(matrix(1:9, nrow = 3))
mat[1, 3] = "12:14"
mat[2, 1] = "18:48"
mat[2, 2] = "10:10"
# using the "which()" option
which(mat == "10:10", arr.ind = TRUE)
# the expected result is (may be in a vector type):
# > "18:48"
# using the "sapply()" option
sapply(colnames(mat), function(x) grep(":", mat[, x]))
# the expected result is (may be in a vector type):
# > "18:48", "10:10", "12:14"
# if I use grepl() rather than grep()
text = mat[sapply(colnames(mat), function(x) grepl(":", mat[, x])), ]
# I get an unexpected result as:
# > text
# V1 V2 V3
# 2 18:48 10:10 8
# NA <NA> <NA> <NA>
# NA.1 <NA> <NA> <NA>