df$varname is a column of df.
df["varname"] is a one-column df containing that column.
df[["varname"]] is a column of df (same as df$varname).
df[,"varname"] is a column of df (same as df$varname).
df[,"varname",drop=FALSE] is a one-column df (same as df$varname).
df$newVarname <- df["varname"] inserts a new component
into df, the component being a one-column data.frame,
not the column in that data.frame.
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Albert-Jan Roskam
> Sent: Friday, June 17, 2011 1:49 PM
> To: R Mailing List
> Subject: [R] is this a bug?
>
> Hello,
>
> Is the following a bug? I always thought that df$varname <-
> does the same as
> df["varname"] <-
>
> > df <- data.frame(weight=round(runif(10, 10, 100)),
> sex=round(runif(100, 0,
> 1)))
> > df$pct <- df["weight"] / ave(df["weight"],
df["sex"], FUN=sum)*100
> > names(df)
> [1] "weight" "sex" "pct" ###
----------> ok
> > head(df)
> weight sex weight ### ----------> huh!?!
> 1 86 0 2.4002233
> 2 19 1 0.5643006
> 3 32 0 0.8931063
> 4 87 0 2.4281328
> 5 45 0 1.2559308
> 6 95 0 2.6514094
> > rm(df)
> > df <- data.frame(weight=round(runif(10, 10, 100)),
> sex=round(runif(100, 0,
> 1)))
> > df["pct"] <- df["weight"] /
ave(df["weight"], df["sex"],
> FUN=sum)*100 ###
> >-----> this does work
> > names(df)
> [1] "weight" "sex" "pct"
> > head(df)
> weight sex pct
> 1 15 0 0.5246590
> 2 43 0 1.5040224
> 3 17 1 0.9284544
> 4 44 1 2.4030584
> 5 76 1 4.1507373
> 6 59 0 2.0636586
> > do.call(c, R.Version())
> platform arch
> "i686-pc-linux-gnu"
"i686"
> os system
> "linux-gnu" "i686,
linux-gnu"
> status major
> ""
"2"
> minor year
> "11.1"
"2010"
> month day
> "05"
"31"
> svn rev language
> "52157"
"R"
> version.string
> "R version 2.11.1 (2010-05-31)"
> > # Thanks!
>
> Cheers!!
> Albert-Jan
>
>
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> All right, but apart from the sanitation, the medicine,
> education, wine, public
> order, irrigation, roads, a fresh water system, and public
> health, what have the
> Romans ever done for us?
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>