Alex
Alex

Reputation: 2077

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). I am running into problems, however, naming the variables of the new data.frame object. 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:

  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?

Upvotes: 0

Views: 93

Answers (2)

Ernest A
Ernest A

Reputation: 7839

You can use 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

Upvotes: 0

bgoldst
bgoldst

Reputation: 35314

The easiest way is probably to just copy the old data.frame in its entirety, and then assign every cell to your new value:

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:

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

Upvotes: 1

Related Questions