Let's say I want to make a data frame with a numeric column and a character column:
df<-data.frame()
for(i in 1:26) {
df<-rbind(df, cbind(x=i, y=toString(i)))
}
str(df)
'data.frame': 26 obs. of 2 variables:
$ x: Factor w/ 26 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
..- attr(*, "names")= chr "x" "x" "x" "x" ...
$ y: Factor w/ 26 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
..- attr(*, "names")= chr "y" "y" "y" "y" ...
Oops, I didn't want factors.
df2<-data.frame()
for(i in 1:26) {
df2<-rbind(df2, cbind(x=i, y=toString(i)), stringsAsFactors=FALSE)
}
str(df2)
'data.frame': 26 obs. of 2 variables:
$ x: chr "1" "2" "3" "4" ...
$ y: chr "1" "2" "3" "4" ...
Now everything is a character. The only way I can figure out to avoid this is by constructing separate vectors and then forming the data frame at the end:
x<-NULL
y<-NULL
for(i in 1:26) {
x<-c(x, i)
y<-c(y, toString(i))
}
df3<-data.frame(x, y, stringsAsFactors=FALSE)
str(df3)
'data.frame': 26 obs. of 2 variables:
$ x: int 1 2 3 4 5 6 7 8 9 10 ...
$ y: chr "1" "2" "3" "4" ...
But as you can see, this requires extra code. If you have a data frame with 20 columns, you need 20 initialization statements before the loop and 20 statements inside the loop to add to the vectors.
Is there a more concise way of accomplishing this?