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

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

问题描述

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

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.

我正在尝试为此循环添加列,遍历 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天全站免登陆