Can someone explain why in the below example the column name for why appears to remain x even though it is clearly named why and can be called as such but not for the column zz?
df<-data.frame(x=1:5,y=1:5)
df$z<-"a"
df$zz<-df$x*df$y
df$why<-df[1]*df[2]
df
df["why"]
Because you’re actually storing a dataframe into why – not a vector.
df[1]returns the first element of df as a sublist. A dataframe is a special type of list which is why you can use this type of indexing to grab columns. However only using the single bracket tells it to return a sublist containing the element of interest (instead of just the element of interest).