R返回行名称的部分匹配 [英] R returning partial matching of row names

查看:78
本文介绍了R返回行名称的部分匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下问题

vec <- c("a11","b21","c31")
df <- data.frame(a = c(0,0,0), b = c(1,1,1), row.names = vec)
df["a",]

返回

df["a",]
    a b
a11 0 1

然而,

"a" %in% vec 

"a" %in% rownames(df) 

都返回False

R允许部分匹配字符串.我已经在R v3.2.2和R v3.2.1上复制了此代码.偶

R is allowing for partial matching of the string when using letter followed by numbers for row names. I have replicated this on R v3.2.2 and R v3.2.1. Even

df[["a",1,exact=T]]

返回0

有什么我可以设置为R不允许部分匹配的内容吗?

Is there anything I can set such that R does not allow this partial matching?

推荐答案

很奇怪,甚至没有意识到部分匹配是一回事.

Weird, didn't even realize the partial matching was a thing.

您可以尝试标识分别与行名完全匹配的记录,而不是直接索引到数据框中,并根据结果构造索引向量,如下所示:

Instead of indexing into the dataframe directly, you could try to identify records that exact match on rowname separately and construct an indexing vector from the result, like so:

> ix <- 'a' == row.names(df)
> df[ix,]
<0 rows> (or 0-length row.names)

或同等(但更简洁):

> df['a' == row.names(df),]

或者,如果将对象强制到data.table,它将仅返回完全匹配项:

Alternatively, if you coerce the object to a data.table it will only return exact matches:

> library(data.table)
> dt <- data.table(df)
> dt[,ix := vec]
> setkey(dt, ix)

> dt['a']
    a  b ix
1: NA NA  a

> dt['a11']
   a b  ix
1: 0 1 a11

这篇关于R返回行名称的部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆