R returning partial match of string names

I ran into the following problem

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

returns

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

but

"a" %in% vec 

and

"a" %in% rownames(df) 

both return false

R allows partial string matching when using a letter followed by numbers for string names. I reproduced this on R v3.2.2 and R v3.2.1. Even

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

returns 0

Is there anything I can set in such a way that R does not allow this partial match?

+4
source share
2 answers

Strange, I didn’t even understand that partial coincidence is a thing.

Instead of directly indexing in the dataframe, you can try to determine the records that exactly match the name rowname and build the indexing vector from the result, for example:

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

( ):

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

, , :

> 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
+4

:

df[grep(pattern = "a", x = rownames(df)),]

:

> df[grep(pattern = "a", x = rownames(df)),]
    a b
a11 0 1

grep , , , a:

> df[grep(pattern = "^a$", x = rownames(df)),]
[1] a b
<0 rows> (or 0-length row.names)
+1

Source: https://habr.com/ru/post/1619572/


All Articles