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

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

问题描述

我有一个数据帧,df,已经有一些数据列。我有一个矢量,namevector,充满了字符串。我需要将空列添加到df中,并使用namevector的列名。



我正在尝试使用此for循环添加列,并在namevector中迭代每个字符串。 / p>

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

但是留下了这个错误。



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



或者,我想到创建一个具有正确名称的空数据框,然后将两个数据框一起,但我不知道如何编写这个。



我将如何解决这个问题?

解决方案

您的代码问题符合以下条件:

  for(i in length(namevector))

你需要问自己:什么是 length(namevec tor)?这是一个数字。所以基本上你在说:

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

或更简单:

  df [,11]<  -  NA 

/ strong>为什么你得到一个错误。你想要的是:

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

或更简单:

 code> df [,namevector]<  -  NA 


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

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