-1

Suppose in one data frame I have, (they are strings)

data1<-data.frame(c("number1","number2"),c("dog,cat","pigeon,leopard"))

and in another data frame I have

 data2<-data.frame(c("pigeon","leopard","dog","cat"),
                   c("5 6 7 8","10 11 12 13","1 2 3 4","5 6 7 8"))

data2:

pigeon      5  6  7  8

leopard    10  11 12 13

dog         1  2   3  4

cat        5   6  7  8

My expected output is a 3-d matrix which would give me:

i=number1/number2

j=the strings corresponding to i

k=the values from the 2nd data frame.

That is I will have, if i select number1,

dog   1 2 3 4 
cat   5 6 7 8 
alko989
  • 7,688
  • 5
  • 39
  • 62
user2458552
  • 419
  • 2
  • 5
  • 17
  • Please provide [reproducible data](http://stackoverflow.com/a/5963610/1412059). Btw, a "3-D matrix" is called an array in R. – Roland Jun 25 '14 at 12:29
  • You should start by bringing your data in a decent format. E.g., make use of `strsplit`. – Roland Jun 25 '14 at 12:55
  • after using unlist(strsplit())..then? – user2458552 Jun 25 '14 at 12:56
  • Are you sure you need a 3d array? If yes, what value you expect for `your3darray["number1", "pigeon", ]`? Wouldn't be enough to add an extra column in data2 with number1 and number2? – alko989 Jun 25 '14 at 16:22

2 Answers2

0

It seems that you just want an extra column in data2 with "number1" and "number2" in the correct places and not really a 3d array.

data2 <- data.frame(j = c("pigeon","leopard","dog","cat"), 
                    k = c("5 6 7 8","10 11 12 13","1 2 3 4","5 6 7 8"), 
                    i = c("number2", "number2", "number1", "number1")) 

Then you can choose everything for "number1" using

data2[data2$i == "number1", ]

If you don't like to have the i column in the result you can do:

data2[data2$i == "number1", ][c("j", "k")]
##     j       k
## 3 dog 1 2 3 4
## 4 cat 5 6 7 8
alko989
  • 7,688
  • 5
  • 39
  • 62
0

I'm not sure I understand your question, but if you want to select by numbers form data1 in data2 you could do

lapply(seq_along(data1[, 1]), function(i) data2[data2[, 1] %in% strsplit(as.character(data1[i, 2]), ",")[[1]],])

which will resolve in a list of matrices

# [[1]]
# c..pigeon....leopard....dog....cat.. c..5.6.7.8....10.11.12.13....1.2.3.4....5.6.7.8..
# 3                                  dog                                           1 2 3 4
# 4                                  cat                                           5 6 7 8
# 
# [[2]]
# c..pigeon....leopard....dog....cat.. c..5.6.7.8....10.11.12.13....1.2.3.4....5.6.7.8..
# 1                               pigeon                                           5 6 7 8
# 2                              leopard                                       10 11 12 13
David Arenburg
  • 91,361
  • 17
  • 137
  • 196