[R] avoid losing data.frame attributes on cbind()

Liviu Andronic landronimirc at gmail.com
Tue Apr 16 20:24:45 CEST 2013


Dear all,
How should I add several variables to a data frame without losing the
attributes of the df? Consider the following:
> require(Hmisc)
> Xa <- iris
> label(Xa, self=T) <- "Some df label"
> str(Xa)
'data.frame':	150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1
1 1 1 1 1 1 ...
 - attr(*, "label")= chr "Some df label"
> Xb <- round(iris[,1:2])
> names(Xb) <- c("var1",'var2')
> Xc <- cbind(Xa, Xb)
> #the attribute is now gone
> str(Xc)
'data.frame':	150 obs. of  7 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1
1 1 1 1 1 1 ...
 $ var1        : num  5 5 5 5 5 5 5 5 4 5 ...
 $ var2        : num  4 3 3 3 4 4 3 3 3 3 ...


In such cases, when I want to plug some variables from 2nd df into the
1st df, how should I proceed without losing the attributes of the 1st
data frame. And, if possible, I'm looking for something nicer than:
for(i in names(Xb)) Xa[ , i] <- Xb[ , i]

Regards,
Liviu



More information about the R-help mailing list