[R] Unexpected result for df column $ subset with non-existent name

Sergei Ko @ggp@@erge| @end|ng |rom gm@||@com
Fri Oct 28 15:52:59 CEST 2022


Hi All,

Just noticed that R returns results for non-existent name if you have
another variable with the same beginning when you subset with $.
See the code below:
name_0 <- "ID"
name_1 <- "name"
name_2 <- "name1"

v0 <- 1:200
v1 <- c(rep(0,100), rep(1,100))
v2 <- c(rep(0,50), rep(1,150))

df <- as.data.frame(cbind(v0, v1, v2))
colnames(df) <- c(name_0, name_1, name_2)

df_1 <- df[, c(name_0, name_1)]
df_2 <- df[, c(name_0, name_2)]

table(df$name)
table(df_1$name)
table(df_2$name)
colnames(df_2)[2] <- "name10"
table(df_2$name)
colnames(df_2)[2] <- "name_any"
table(df_2$name)
table(df_2[,"name"])

The last row produces an error as intended.
Any ideas?

Win 10
R version 4.2.1 (2022-06-23 ucrt) -- "Funny-Looking Kid"

Regards,
Sergiy

	[[alternative HTML version deleted]]



More information about the R-help mailing list