user2543622
user2543622

Reputation: 6766

convert vector to dataframe when vector's name is changing

Below piece of code works as i want

d=c(0,1)
A1=c(0,1)
A2=c(0,1)
d=as.data.frame(d)
A1=as.data.frame(A1)
A2=as.data.frame(A2)
d=merge(d,A1)
d=merge(d,A2)

It produces below d

> d
  d A1 A2
1 0  0  0
2 1  0  0
3 0  1  0
4 1  1  0
5 0  0  1
6 1  0  1
7 0  1  1
8 1  1  1

I want below piece of code to behave exactly like above code

steps=3
ball_numbers=c(4,5,6)
d=as.data.frame(c(0,1))

for (i in (1:length(ball_numbers)-1))
{
  assign(paste("A", i, sep = ""),c(0,1))
#how to convert variables on earlier step to dataframes?

  d=merge(d,get(paste("A", i, sep = "")))
}

this code produces different d, when I am expecting d as shown in the first set above

  y c(0, 1)
1 0       0
2 0       1
3 1       0
4 1       1

How could i ensure that I get same d in case of the second set of code?

Upvotes: 1

Views: 60

Answers (2)

David Arenburg
David Arenburg

Reputation: 92292

I would suggest to avoid messing around with assign for various reasons, instead you could just create a simple function which will utilize expend.grid, for instance:

combs <- function(nums, vec) {
  res <- replicate(length(nums), vec, simplify = FALSE)
  setNames(expand.grid(res), c("d", paste0("A", 1:(length(nums)-1))))
}


ball_numbers <- 4:6
d <- 0:1
combs(ball_numbers, d)
#   d A1 A2
# 1 0  0  0
# 2 1  0  0
# 3 0  1  0
# 4 1  1  0
# 5 0  0  1
# 6 1  0  1
# 7 0  1  1
# 8 1  1  1

Upvotes: 2

Buzz Lightyear
Buzz Lightyear

Reputation: 844

This should work.

The basic problem was that each of your vectors had the same column names and so the merge wasn't occurring properly.

steps=3
ball_numbers=c(4,5,6)
d=as.data.frame(c(0,1))
colnames(d) <- c("d")

for (i in (1:(length(ball_numbers)-1))){
   assign(x = paste("A", i, sep = ""),value = c(0,1))
   e <- as.data.frame(get(paste("A", i, sep = "")))
   colnames(e) <- paste("A", i, sep="")
   d <- merge(d,e)
}

You need to create the temp variable so that you can rename the column.

Upvotes: 1

Related Questions