I have a dataframe, df, with a a number of columns of data already. I have a vector, namevector, full of strings. I need empty columns added to df with the names of the columns from namevector.

I am trying to add columns with this for loop, iterating over each string in namevector.

for (i in length(namevector)) {
  df[, i] <- NA
}

but am left with this error:

Error in [<-.data.frame(*tmp*, , i, value = NA) : new columns would leave holes after existing columns

Alternatively, I have thought of creating an empty dataframe with the correct names, then cbind-ing the two dataframes together but am not sure how to go about coding this.

How would I go about resolving this?

推荐答案

The problem with your code is in the line:

for(i in length(namevector))

You need to ask yourself: what is length(namevector)? It's one number. So essentially you're saying:

for(i in 11)
df[,i] <- NA

Or more simply:

df[,11] <- NA

That's why you're getting an error. What you want is:

for(i in namevector)
    df[,i] <- NA

Or more simply:

df[,namevector] <- NA

R相关问答推荐

R根据条件进行累积更改

一小时满足条件的日期的 Select

如何读取CSV的特定列时,给定标题作为向量

如何基于两个条件从一列中提取行

按时间顺序对不同事件进行分组

为左表中的所有行使用值Fill滚动左连接

如何使用For-R循环在向量中找到一系列数字

使用列中的值来调用函数调用中应使用的其他列

有毒元素与表观遗传年龄的回归模型

为什么将负值向量提升到分数次方会得到NaN

我正在try 创建一个接近cos(X)的值的While循环,以便它在-或+1-E10范围内

使用一个标签共享多个组图图例符号

如何创建直方图与对齐的每月箱?

对计算变量所有唯一值的变量进行变异

如何根据列名和行名求和矩阵的值?

可以在R中同步3D散点图(打印)吗?

将向量列表高效地转换为矩阵

R中按组划分的总计数百分比

用于熵平衡的R包ebal:错误消息

如何在gg散点图中增加自动生成的R和p值的字体大小?