If you have a data.frame
say, "DF", like this:
DF <- data.frame(x=1:9, y=letters[1:9])
And you've a vector
z:
z <- c(0, 1, 0, 0, 0, 0, 0, 0, 0)
Note that the number of rows in your data.frame
and the length of the vector
has to be the same if you want to add the vector
to a data.frame
as a new column.
dim(DF) # dimensions of data.frame
# [1] 9 2
length(z) # length of vector
# [1] 9
Now, you can use cbind
to get the new column as follows:
cbind(DF, z)
# x y z
# 1 1 a 0
# 2 2 b 1
# 3 3 c 0
# 4 4 d 0
# 5 5 e 0
# 6 6 f 0
# 7 7 g 0
# 8 8 h 0
# 9 9 i 0
If you have a vector
whose length is not equal to that of the data.frame
rows, then,
z <- c(0, 1, 0, 0, 0, 0, 0) # length is 7
cbind(DF, z)
# Error in data.frame(..., check.names = FALSE) :
# arguments imply differing number of rows: 9, 7
cbind
'ing results in error due to unequal lengths. In this case, I could think of a couple ways to store this as a list
.
First, you can keep your data.frame
DF as such and create a list
with its first element as the data.frame
and the second as a vector
as follows:
my_l <- list(d1 = DF, d2 = z)
# $d1
# x y
# 1 1 a
# 2 2 b
# 3 3 c
# 4 4 d
# 5 5 e
# 6 6 f
# 7 7 g
# 8 8 h
# 9 9 i
#
# $d2
# [1] 0 1 0 0 0 0 0
Alternatively, you can convert your data.frame
to a list
(a data.frame
is internally a list
) and create a list
whose elements are all vectors
as follows:
my_l <- c(as.list(DF), list(z=z))
# $x
# [1] 1 2 3 4 5 6 7 8 9
#
# $y
# [1] a b c d e f g h i
# Levels: a b c d e f g h i
#
# $z
# [1] 0 1 0 0 0 0 0
Note that as.list
coerces a data.frame
columns to a list
with it's names the column names of the data.frame
. We then create a new list
z and then concatenate
using the c
operator.
Hope this betters your understanding a bit.