简体   繁体   中英

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.

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)))

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
    x[(nrow(x)+1):(nrow(x)+length(y)),] <- y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM