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

Bert Gunter bgunter@4567 @end|ng |rom gm@||@com
Fri Oct 28 16:25:28 CEST 2022


Does this explain it: (from ?Extract)


name
A literal character string or a name (possibly backtick quoted). For
extraction, this is normally (see under ‘Environments’) **partially
matched** to the names of the object.

-- Bert

On Fri, Oct 28, 2022 at 6:53 AM Sergei Ko <sggp.sergei using gmail.com> wrote:
>
> 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]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list