José Baltazar
José Baltazar

Reputation: 11

How do I add observations to an existing data frame column?

I have a data frame. Let's say it looks like this:

Input data set

I have simulated some values and put them into a vector c(4,5,8,8). I want to add these simulated values to columns a, b and c.

I have tried rbind or inserting the vector into the existing data frame, but that replaced the existing values with the simulated ones, instead of adding the simulated values below the existing ones.

x <- data.frame("a" = c(2,3,1), "b" = c(5,1,2), "c" = c(6,4,7))
y <- c(4,5,8,8)

This is the output I expect to see:

Output

Help would be greatly appreciated. Thank you.

Upvotes: 1

Views: 220

Answers (3)

akrun
akrun

Reputation: 887901

An option is assignment

n <- nrow(x)
x[n + seq_along(y), ] <- y
x
#  a b c
#1 2 5 6
#2 3 1 4
#3 1 2 7
#4 4 4 4
#5 5 5 5
#6 8 8 8
#7 8 8 8

Another option is replicate the 'y' and rbind

rbind(x, `colnames<-`(replicate(ncol(x), y), names(x)))

Upvotes: 1

Yiqun
Yiqun

Reputation: 39

    x[(nrow(x)+1):(nrow(x)+length(y)),] <- y

Upvotes: 0

NelsonGon
NelsonGon

Reputation: 13319

Can do:

  as.data.frame(sapply(x, 
               function(z) 
                 append(z,y)))
  a b c
1 2 5 6
2 3 1 4
3 1 2 7
4 4 4 4
5 5 5 5
6 8 8 8
7 8 8 8

Upvotes: 1

Related Questions