[R] Unexpected result for df column $ subset with non-existent name
Rui Barradas
ru|pb@rr@d@@ @end|ng |rom @@po@pt
Fri Oct 28 17:42:41 CEST 2022
Às 14:52 de 28/10/2022, Sergei Ko escreveu:
> 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.
Hello,
This behavior, partial matching of column or list members names when
extracting with `$` is practically a FAQ.
See the latest R-Help thread on it after the release of R 4.0
https://stat.ethz.ch/pipermail/r-help/2020-May/467143.html
Hope this helps,
Rui Barradas
More information about the R-help
mailing list