如何在data.table中找到特定字符串的行号和列号?

时间:2019-03-18 08:15:58

标签: r data.table

假设我有以下data.table:

DT <- setDT(data.frame(id = 1:10, LETTERS = LETTERS[1:10], 
            letters = letters[1:10]))


##+ > DT
##     id LETTERS letters
##  1:  1       A       a
##  2:  2       B       b
##  3:  3       C       c
##  4:  4       D       d
##  5:  5       E       e
##  6:  6       F       f
##  7:  7       G       g
##  8:  8       H       h
##  9:  9       I       i
## 10: 10       J       j

,我想找到字母“ h”的行号和列号(分别为8和3)。我该怎么办?

2 个答案:

答案 0 :(得分:3)

DT[, which(.SD == "h", arr.ind = TRUE)]

#      row col
# [1,]   8   3

编辑:

试图考虑迈克尔的观点:

str_idx = which(sapply(DT, function(x) is.character(x) || is.factor(x)))
idx <- DT[, which(as.matrix(.SD) == "h", arr.ind = TRUE), .SDcols = str_idx]
idx[, "col"] <- chmatch(names(str_idx)[idx[, "col"]], names(DT))
idx 

#     row col
# [1,]   8   3

答案 1 :(得分:2)

取决于所需输出的确切格式。

tooltips = [
    ("fruit", "@fruits"),
    ("x, y", "$x,$y"),
]

p = figure(x_range=fruits, plot_height=300, title="Fruit Counts by Year",
           toolbar_location="right", tools=["hover"], tooltips = tooltips)

还应该# applying to non-string columns is inefficient str_idx = which(sapply(DT, is.character)) # returns a list as long as str_idx with two elements appropriately named lapply(str_idx, function(jj) list(row = which(DT[[jj]] == 'h'), col = jj)) 表中的字符串列以避免循环。