简体   繁体   English

如何将观测值添加到现有数据框列?

[英]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). 我已经模拟了一些值,并将它们放入向量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: 这是我期望看到的输出:

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 另一种选择是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.

相关问题 如何将列添加到使用包含现有列变量的数学方程的数据框中? - How Do I add column to data frame that uses a mathematical equation with variables from the existing columns? 如何将数据框中的观测值数量存储到变量中? - How do I store the number of observations in a data frame into a variable? 如何按数据框中的列名重命名观察结果? - How to rename observations by column name in data frame? 如何通过对每个站点的观测值求和来添加一列丰度数据? - How do I add a column of abundance data by summing observations per site? 如何创建具有与现有data.frame相同的列名和类型的新data.frame? - How do I create a new data.frame with the same column names and types as an existing data.frame? 如何向列表中的每个数据框添加一列 - How do I add a column to each data frame in a list 如何使用 terra 将 shapefile 列添加到提取的数据框中? - How do I add shapefile column to extracted data frame with terra? 如何在 R 的数据框中添加新列并使用现有列? - How can I add a new column and use an existing column in a data frame in R? 如何在R中的数据框中添加列 - How do add a column in a data frame in R 如何在现有data.frame中添加其他列,这些列在data.frame中已有的一个特定列上对齐? - How can I add additional columns to an existing data.frame, that are aligned on one specific column already in the data.frame?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM