-1

I have two lists. The first (List1) consists of 126 items, each of which is a dataframe with 240 observations of 13 variables, like so:

List1          Large List (126 elements, 3.2 Mb)
:'data.frame': 240 obs. of 13 variables
..$X1: num [1:240] 1.5 2.3 6.4 3.3 ...
..$X2: num [1:240] 3.8 9.4 0.4 6.4 ...
.................................................
:'data.frame': 240 obs. of 13 variables
..$X1: num [1:240] 2.6 0.9 0.5 3.7 ...
..$X2: num [1:240] 4.9 5.5 5.6 3.1 ...
.................................................

List2 also consists of 126 items, but this time is just 1 observation of 13 variables, like so:

List2          List of 126
: num[1, 1:13] 5.5 4.2 6.3 9.2 ...
: num[1, 1:13] 2.1 1.4 7.7 3.9 ...
.................................................

I am simply attempting to subtract List2 from List1. In other words, I want to subtract the 13 numbers in each element of List2 from all 240 lines in each element of List1. This should give me 126 new items in a list, with 240 observations of 13 variables.

I have tried:

ANOM=Map(function(x,y) x-y, List1, List2)

and this does work, but it doesn't give the right result as it does not delete the correct columns from List2 from the correct columns of List1. Is there something simple I might be doing wrong here?

DJ-AFC
  • 569
  • 6
  • 16
  • I guess you've heard about how reproducible examples are helpful on this site, but here's another reference anyway: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/28481250#28481250 – Frank Nov 21 '16 at 22:11
  • Apologies. I tried to make this question as clear as possible, but found it difficult. I will delete the question I think. – DJ-AFC Nov 21 '16 at 22:32
  • I think the question is a decent one, but you need to clarify what you mean by _subtract List2 from List1_. Do you mean something like `list(List1[[1]] - List2[[0]], List1[[2]] - List2[[2]],...,List1[[126]]-List2[[126]])`? or `for each row in List2 List1[1] - row ...`? Also share some dummy data. – Abdou Nov 21 '16 at 22:36
  • Thanks Abdou - it's the second one here. I wish to List 2 from each row of list 1. – DJ-AFC Nov 21 '16 at 22:41
  • @DJ-AFC, You mean something like `lapply(List1, function(dff) { dff - Reduce('+',List2) })`? – Abdou Nov 21 '16 at 22:59

1 Answers1

0

See if this works?

list3=list()
for(i in 1:length(list1))list3[[i]]=list1[[i]]-rep(1,240)%*%list2[[i]]
str(list3)
Robert
  • 5,038
  • 1
  • 25
  • 43
  • Thanks for the comment - unfortunately this returns precisely the same output as the map function I outlined in my example. – DJ-AFC Nov 21 '16 at 22:40
  • try the edit and see if it works? – Robert Nov 22 '16 at 00:03
  • Thanks @Robert - that solution does the trick. I guess repeating the second list was necessary to make the lists consist of equally structured data frames. – DJ-AFC Nov 22 '16 at 08:20