I have a set of 50 vectors and would like to create a dataframe from those 50 vectors values and their names as the following example.
Example with 3 vector, but reality is about 50 vectors.
vector_a<- c("a1","a2", "a3","a4")
vector_cx<- c("1","2","3")
vector_3 <-c("x1","x2")
Expected result.
data.frame(values=c("a1","a2", "a3","a4","1","2","3","x1","x2"),
vector_names=c("vector_a","vector_a", "vector_a","vector_a","vector_cx","vector_cx","vector_cx","vector_3","vector_3"))
The code above produces the following table.
values vector_names
1 a1 vector_a
2 a2 vector_a
3 a3 vector_a
4 a4 vector_a
5 1 vector_cx
6 2 vector_cx
7 3 vector_cx
8 x1 vector_3
9 x2 vector_3
CodePudding user response:
Using mget to get vectors into a list, then stack to convert list into a dataframe:
stack(mget(ls(pattern = "^vector_")))
# values ind
# 1 x1 vector_3
# 2 x2 vector_3
# 3 a1 vector_a
# 4 a2 vector_a
# 5 a3 vector_a
# 6 a4 vector_a
# 7 1 vector_cx
# 8 2 vector_cx
# 9 3 vector_cx
CodePudding user response:
Definitely a worse answer compared to the above.
You can also use purrr
to implement a stack
vector_a<- c("a1","a2", "a3","a4")
vector_cx<- c("1","2","3")
vector_3 <-c("x1","x2")
map2_df(list(vector_a, vector_cx), c(deparse(substitute(vector_a)), deparse(substitute(vector_cx))), ~data.frame(.x) %>% mutate(vector_name = .y))
output -----
.x vector_name
1 a1 vector_a
2 a2 vector_a
3 a3 vector_a
4 a4 vector_a
5 1 vector_cx
6 2 vector_cx
7 3 vector_cx