Reputation: 725
I have two data frames df1 and df2 and they are stored inside a list:
$df1
column 1. column 2. column 3
A a6 1
B j7 2
C i0 3
D b2 4
$df2
column 1. column 2. column 3
E 8h 1
F 4d 2
G 3n 3
H a9 4
I 5% 5
L *9. 6
The data frames have different row numbers and are stored in list1 list1<-(df1,df2)
I would like to divide the last column number 3 which represents the rank by the total number of row (divide each value): The row number information is stored in a vector and it is different from the row numbers of those two data frames because they are a subset of a larger data frame with more rows: vec<-c(10,20)
Output:
$df1
$df1 nrow = 4
#df1_ALL nrow = 10
column 1. column 2. column 3
A a6 1/10
B j7 2/10
C i0 3/10
D b2 4/10
$df2
$df2 nrow=6
$df2_ALL nrow = 20
column 1. column 2. column 3
E 8h 1/20
F 4d 2/20
G 3n 3/20
H a9 4/20
I 5% 5/20
L *9. 6/20
I wrote something like this:
list2<-list()
for (i in 1: length(list1)) {
+ list2[[i]]<- sweep(list1[[i]]$column3, 1,vec,'/')
+ }
however is giving me the following error:
Error in array(STATS, dims[perm]) : 'dims' cannot be of length 0
In addition: Warning message:
In sweep(myfiles[[i]]$rank, 1, g1, "/") :
STATS is longer than the extent of 'dim(x)[MARGIN]'
Any help it would be great, cheers
Upvotes: 3
Views: 85
Reputation: 887008
We loop through the list
of datasets, with Map
and transform
to divide the last column by the number of rows of that dataset stored in a vector
('vec')
Map(function(x, y) transform(x, `column 3` = `column 3`/y), list1, vec)
Upvotes: 2