0

Let I have two lists(list1 and list2) where each elements are data frame:

list1[1]

    col1 col2
    12   3
    9    5

list1[2]

    col1 col2
    4    11
    10   7


list2[1]

    col1 col2
    b    b
    b    a

list1[2]

    col1 col2
    a    b
    b    a

Desired output list3 is:

list3[1]

    col1 col2
    0    5
    0    0

list3[2]

    col1 col2
    4    7
    0    0

Namely, in list3,

i'th data frame is equal to values of i'th data frame in list1 conditional to i'th data frame in list2 equals to "a".

However, if element list2 is not equal to "b", 0 added end of each column of related each data frame in list3.

How can I do that uisng R? I will be very glad for any help. Thanks a lot.

oercim
  • 1,808
  • 2
  • 17
  • 34
  • Please post code that creates such a structure, or use dput for posting of an example that you are working with. (You have tried working on your own example, right?) – IRTFM Mar 15 '15 at 19:21

1 Answers1

2
list1 <- list(data.frame(col1 = c(12, 9), col2 = c(3, 5)), data.frame(col1 = c(4, 10), col2 = c(11, 7)))
list2 <- list(data.frame(col1 = c("b", "b"), col2 = c("b", "a")), data.frame(col1 = c("a", "b"), col2 = c("b", "a")))

#Generate a list of matrices with the coordinates of "a"
ind <- lapply(list2, function(x) which(x == "a", arr.ind = TRUE))
ind_fin <- lapply(ind, function(x) cbind(along = ave(x[,2], x[,2], FUN = seq_along), x[,2]))

# Generate a list of zero matrices, where you will replace some values
l_zero <- replicate(2,matrix(0,2,2),simplify=FALSE)

# Extract the values you want to put into the other matrix
res <- Map(function(x, y) y[x], x = lapply(list2, function(x) x == "a"), y = list1)

And finally with some help from here

Map("[<-", l_zero, ind_fin, res)
[[1]]
     [,1] [,2]
[1,]    0    5
[2,]    0    0

[[2]]
     [,1] [,2]
[1,]    4    7
[2,]    0    0
Community
  • 1
  • 1
DatamineR
  • 10,428
  • 3
  • 25
  • 45
  • thanks for the help. But your code does not do the exact thing I want. I know, I could not state the problem very clearly. I want to add 0's end of each column of dat aframes. I edited values of list2. Can you try with new values? Thanks a lot again. – oercim Mar 15 '15 at 19:57
  • It's bit more complicated now. Check if this is your desired code – DatamineR Mar 15 '15 at 23:06
  • thanks a lot for sparing your time. Your code works very well for 2x2 matrix. But for general matrices, it does not work. It is my fault not to state it. I need such a method for general matrices(data frames-in lists all data frames are equal length but size can be anything, not just 2x2). Your solution gained me a lot. I will be working on it. Thanks a lot again. – oercim Mar 16 '15 at 18:44
  • I editted the answer (the code for `ind_fin`) and it should now work for more general cases, not only `2x2` matrices. You only need to adapt the `l_zero` accordingly. Check it and if there are any problems let me know – DatamineR Mar 16 '15 at 21:15