user2813606
user2813606

Reputation: 921

RBIND numeric vectors (R)

I am having some trouble using rbind to join a series of numeric vectors.

Let's say I have:

List1Nums=c(600,500,400,300,200)
List2Nums=c(550,450,350)
List3Nums=c(275,375,475,575)
List4Nums=c(310,410,510,610)

List1=rep(1,length(List1Nums))
List2=rep(2,length(List2Nums))
List3=rep(3,length(List3Nums))
List4=rep(4,length(List4Nums))

I want to use rbind() to join the series of List#Nums and List# so I would have a data frame that looks like:

Nums   List
600    1
500    1
400    1
300    1
200    1
550    2
450    2
…      ... 

I tried using:

 Nums=rbind(List1Nums,List2Nums,List3Nums,List4Nums)
 List=rbind(List1,List2,List3,List4)
 data=cbind(Nums,List)

I get an error message that reads:

Warning message:
  number of columns of result is not a multiple of vector length (arg 2)

Can someone help point me in the right direction?

Thank you!

Upvotes: 0

Views: 187

Answers (2)

akrun
akrun

Reputation: 887501

One option is mget to get the values of all the 'ListdigitNums' objects in a list, and stack it to a two column data.frame

lst1 <- mget(ls(pattern = "^List\\d+Nums$"))
setNames(stack(setNames(lst1, seq_along(lst1))), c("Nums", "List"))
#   Nums List
#1   600    1
#2   500    1
#3   400    1
#4   300    1
#5   200    1
#6   550    2
#7   450    2
#8   350    2
#9   275    3
#10  375    3
#11  475    3
#12  575    3
#13  310    4
#14  410    4
#15  510    4
#16  610    4

This can be also be written as

stack(mget(ls(pattern = "^List\\d+Nums$"))) 

If the 'List' values can be the object names


If we also need to use the List1, List2, etc, vectors

 do.call(rbind, Map(cbind, mget(ls(pattern = "^List\\d+Nums$")), 
          mget(paste0("List", 1:4))))

Upvotes: 2

Bill Chen
Bill Chen

Reputation: 1749

You can do this also:

> Nums=c(List1Nums,List2Nums,List3Nums,List4Nums)
> List=c(List1,List2,List3,List4)
> data=cbind(Nums,List)
> 
> data
      Nums List
 [1,]  600    1
 [2,]  500    1
 [3,]  400    1
 [4,]  300    1
 [5,]  200    1
 [6,]  550    2
 [7,]  450    2
 [8,]  350    2
 [9,]  275    3
[10,]  375    3
[11,]  475    3
[12,]  575    3
[13,]  310    4
[14,]  410    4
[15,]  510    4
[16,]  610    4

Upvotes: 2

Related Questions