DJ-AFC DJ-AFC - 14 days ago 5
R Question

Subtracting lists with different data structures

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?

Answer

See if this works?

list3=list()
for(i in 1:length(list1))list3[[i]]=list1[[i]]-rep(1,240)%*%list2[[i]]
str(list3)