[英]How do I add observations to an existing data frame column?
I have a data frame. 我有一个数据框。 Let's say it looks like this:
假设它看起来像这样:
I have simulated some values and put them into a vector c(4,5,8,8). 我已经模拟了一些值,并将它们放入向量c(4,5,8,8)中。 I want to add these simulated values to columns a, b and c.
我想将这些模拟值添加到列a,b和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. 我尝试了
rbind
或将向量插入到现有数据帧中,但是用模拟值替换了现有值,而不是在现有值下方添加模拟值。
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: 这是我期望看到的输出:
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
另一种选择是
replicate
'y'和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.