简体   繁体   English

子集字符向量以在data.frame中创建列

[英]Subsetting character vector to create columns in data.frame

I am attempting to create a new data.frame object that is composed of the columns of the old data.frame with every row set at a given value (for this example, I will use 7). 我试图创建一个新的data.frame对象,该对象由旧的data.frame的列组成,每行设置为给定值(在本示例中,我将使用7)。 I am running into problems, however, naming the variables of the new data.frame object. 但是,在命名新的data.frame对象的变量时遇到了问题。 Here is what I'm trying to do: 这是我想要做的:

my.df <- data.frame(x = 1:3, y123=4:6)

my.df
  x y123
1 1    4
2 2    5
3 3    6

Then when I attempt to assign these variable names to the new data.frame : 然后,当我尝试将这些变量名称分配给新的data.frame

  the.names <- names(my.df)

for(i in 1:length(the.names)){
  data.frame(
    the.names[i] = 7
  )
}

But this throws errors with unexpected =, ), and }. 但这会引发意外的=,)和}错误。 This would usually make me suspect a typo, but I've reviewed this several times and can't find anything. 通常,这会让我怀疑是错字,但是我已经对此进行了数次审查,但找不到任何东西。 Any ideas? 有任何想法吗?

The easiest way is probably to just copy the old data.frame in its entirety, and then assign every cell to your new value: 最简单的方法可能是完全复制旧的data.frame,然后将每个单元格分配给您的新值:

df <- data.frame(x=1:3,y123=4:6);
df2 <- df;
df2[] <- 7;
df2;
##   x y123
## 1 7    7
## 2 7    7
## 3 7    7

If you only want one row in the new data.frame, you can index only the top row when making the copy: 如果仅在新的data.frame中需要一行,则在进行复制时只能索引第一行:

df <- data.frame(x=1:3,y123=4:6);
df2 <- df[1,];
df2[] <- 7;
df2;
##   x y123
## 1 7    7

Edit: Here's how you can set each column to a different value: 编辑:这是将每列设置为不同值的方法:

df <- data.frame(x=1:3,y123=4:6);
df2 <- df;
df2[] <- rep(c(7,31),each=nrow(df2));
df2;
##   x y123
## 1 7   31
## 2 7   31
## 3 7   31

You can use within : 您可以within使用:

> within(my.df, {
+     assign(the.names[1], 0)
+     assign(the.names[2], 1)
+ })
  x y123
1 0    1
2 0    1
3 0    1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM