[R] Bug in print for data frames?

Iris Simmons |kw@|mmo @end|ng |rom gm@||@com
Thu Oct 26 10:46:03 CEST 2023


I would say this is not an error, but I think what you wrote isn't
what you intended to do anyway.

y[1] is a data.frame which contains only the first column of y, which
you assign to x$C, so now x$C is a data.frame.

R allows data.frame to be plain vectors as well as matrices and
data.frames, basically anything as long as it has the correct length
or nrow.

When the data.frame is formatted for printing, each column C is
formatted then column-bound into another data.frame using
as.data.frame.list, so it takes the name A because that's the name of
the column from y.

I think what you meant to do is x$C <- y[[1]]  ## double brackets
instead of single

On Thu, Oct 26, 2023 at 4:14 AM Christian Asseburg <rhelp using moin.fi> wrote:
>
> Hi! I came across this unexpected behaviour in R. First I thought it was a bug in the assignment operator <- but now I think it's maybe a bug in the way data frames are being printed. What do you think?
>
> Using R 4.3.1:
>
> > x <- data.frame(A = 1, B = 2, C = 3)
> > y <- data.frame(A = 1)
> > x
>   A B C
> 1 1 2 3
> > x$B <- y$A # works as expected
> > x
>   A B C
> 1 1 1 3
> > x$C <- y[1] # makes C disappear
> > x
>   A B A
> 1 1 1 1
> > str(x)
> 'data.frame':   1 obs. of  3 variables:
>  $ A: num 1
>  $ B: num 1
>  $ C:'data.frame':      1 obs. of  1 variable:
>   ..$ A: num 1
>
> Why does the print(x) not show "C" as the name of the third element? I did mess up the data frame (and this was a mistake on my part), but finding the bug was harder because print(x) didn't show the C any longer.
>
> Thanks. With best wishes -
>
> . . . Christian
>
> ______________________________________________
> 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