user3878084 user3878084 - 10 months ago 47
R Question

begginner create vectors using rbind function

Two part question.

Part 1, preface : concerning what am trying to accomplish / what I am trying to do. I want to understand exactly what is happening with (2) below.

To provide context: I don't have a clue as to what type of object the following produces (or what exactly "type" means for that matter), but
the following seems to produce an object which when printed appears to be a column vector (i.e., a matrix with several rows and only one column).


> z = 0
> for (x in unique(sort(df1$Mkt_Area))){
+ y = df1[ which( df1$Mkt_Area == x) , ]
+ z = rbind(z, mean(y$Sale_Price))
+ }
> z
z 0.00

I am confused as to why the following does not appear to have have analogous behavior


> w = 0
> for (x in unique(sort(df1$Mkt_Area))){
+ w = rbind(w, x)
+ }
> w
w 0
x 1101
x 1102
x 1201

In particular, why is the column containing the character x printed in (2) but not (1) ? What is the meaning / significance of that difference?

Part 2. If I wanted to produce column vectors by way of loops analogous to the above (I am not asking whether using loops for that purpose is advisable or how to produce column vectors by alternate means), then how
would I do so if (1) and (2) do not (at this point, I assume they don't)?

Answer Source

Without some example data to play with this is my best guess. They are printing the same type of object, a 1 column matrix. The difference in row names comes up because the object being added in the loop is different. In object 1 you are adding mean(y$Sale_Price) which has no name, so you get z in the for the first row, name coming from object z, and no row names in the rest of the rows. For object 2 you are adding object x. This object has a name so the rest of the rows beyond w have the row name x.

Here is how you would build a similar object without a loop.

matrix(NA,5,1,dimnames = list(rep("a",5)))