将空列添加到具有向量中指定名称的数据框 [英] Add empty columns to a dataframe with specified names from a vector

查看:32
本文介绍了将空列添加到具有向量中指定名称的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,df,已经有许多数据列.我有一个充满字符串的向量 namevector.我需要使用 namevector 中的列名称将空列添加到 df.

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.

我正在尝试使用此 for 循环添加列,迭代 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
}

但我留下了这个错误:

[<-.data.frame(*tmp*, , i, value = NA) 中的错误:新列会在现有列之后留下孔

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

或者,我想用正确的名称创建一个空的数据框,然后 cbind 将两个数据框连接在一起,但我不知道如何进行编码.

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?

推荐答案

问题与您的代码有关:

for(i in length(namevector))

你需要问问自己:什么是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

或者更简单:

df[,11] <- NA

这就是您收到错误的原因.你想要的是:

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

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

或者更简单:

df[,namevector] <- NA

这篇关于将空列添加到具有向量中指定名称的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆