在 R 中,用列表中的向量命名列后,如何找到匹配的列名(grep 和 match give integer(0), NA)?
In R, after naming columns with vectors from a list, how to find a matching column name (grep and match give integer(0), NA)?
我可能漏掉了一些非常简单的东西。我有一个向量列表,然后将其用作列名。现在我希望能够找到给定向量的列(索引)。我已经尝试过 grep 和 match,由于某种原因,当我知道它是我从查看数据框时看到的第一列时,我得到了 NA 和 integer(0)。我究竟做错了什么?代码如下:
#Loops to create S
S <- list()
i <- 1
for(a in 0:12){
for(b in 0:(12-a)){
for(c in 0:(12-a-b)){
for(d in 0:(12-a-b-c)){
e <- 12 - a - b - c - d
S[[i]] <- c(a, b, c, d, e)
i <- i + 1
}
}
}
}
P <- matrix(data = NA, nrow = length(S), ncol = length(S))
for(i in 1:length(S)){
for(j in 1:length(S)){
#lots of stuff
}
}
#Rename P matrix cols/rows
colnames(P) <- S
rownames(P) <- S
#Now I want to find which column has the name "c(0,0,0,0,12)" -- should be first one. I tried:
grep("c(0, 0, 0, 0, 12)", colnames(P))
match('c(0, 0, 0, 0, 12)', names(P))
谢谢。
您 match
尝试的唯一问题是您使用了 names(P)
,并且 names()
没有为矩阵定义。使用 colnames
或 rownames
它将按预期工作:
match("c(0, 0, 0, 0, 12)", colnames(P))
# [1] 1
match("c(1, 5, 4, 0, 2)", colnames(P))
# [1] 758
您的 grep
尝试无效,因为 ()
是正则表达式中的特殊字符。如果您转义括号或设置 fixed = TRUE
,则可以使用 grep
,但您不应该真正使用 grep
来精确匹配整个字符串 - match
或 ==
或 %in%
是更好的工具。当您需要通过正则表达式进行部分匹配或模式匹配时,请保存 grep
。
我可能漏掉了一些非常简单的东西。我有一个向量列表,然后将其用作列名。现在我希望能够找到给定向量的列(索引)。我已经尝试过 grep 和 match,由于某种原因,当我知道它是我从查看数据框时看到的第一列时,我得到了 NA 和 integer(0)。我究竟做错了什么?代码如下:
#Loops to create S
S <- list()
i <- 1
for(a in 0:12){
for(b in 0:(12-a)){
for(c in 0:(12-a-b)){
for(d in 0:(12-a-b-c)){
e <- 12 - a - b - c - d
S[[i]] <- c(a, b, c, d, e)
i <- i + 1
}
}
}
}
P <- matrix(data = NA, nrow = length(S), ncol = length(S))
for(i in 1:length(S)){
for(j in 1:length(S)){
#lots of stuff
}
}
#Rename P matrix cols/rows
colnames(P) <- S
rownames(P) <- S
#Now I want to find which column has the name "c(0,0,0,0,12)" -- should be first one. I tried:
grep("c(0, 0, 0, 0, 12)", colnames(P))
match('c(0, 0, 0, 0, 12)', names(P))
谢谢。
您 match
尝试的唯一问题是您使用了 names(P)
,并且 names()
没有为矩阵定义。使用 colnames
或 rownames
它将按预期工作:
match("c(0, 0, 0, 0, 12)", colnames(P))
# [1] 1
match("c(1, 5, 4, 0, 2)", colnames(P))
# [1] 758
您的 grep
尝试无效,因为 ()
是正则表达式中的特殊字符。如果您转义括号或设置 fixed = TRUE
,则可以使用 grep
,但您不应该真正使用 grep
来精确匹配整个字符串 - match
或 ==
或 %in%
是更好的工具。当您需要通过正则表达式进行部分匹配或模式匹配时,请保存 grep
。