Lucas Sempe
Lucas Sempe

Reputation: 63

Split dataframe and apply function to 2 different rows in R

I'm trying to apply a mi.meld to a list of 144 data frames in order to combine sets of estimates and their standard errors. As Amelia doesn't work with lists, I unnested it into a large data frame, where each 2 rows correspond to the original data frame. Below is a snapshot of my data (288 rows).

I want to find a quick way not to repeat the command 144 times mi.meld(data,q=data[1,],data[2,]), and mi.meld (data,q=data[3,],data[4,]), and 142 more times...

So, in the first case q should be a vector of values of the first row and so on...

Thanks, Lucas

   nn        V1         V2         V3
ARE.1  1 357.85116 356.859011 359.432494
ARE.2  1   8.54784   7.450074   9.711469
ARE.3  2 503.99528 506.120967 507.520785
ARE.4  2  14.52657  12.129299  14.469123
AUS.1  3 421.60845 423.302610 425.196122
AUS.2  3  29.31331  27.230948  28.605672

Upvotes: 0

Views: 90

Answers (2)

r2evans
r2evans

Reputation: 160437

rownum <- seq_len(nrow(mtcars))
split(rownum, (rownum-1) %/% 2)[1:3]
# $`0`
# [1] 1 2
# $`1`
# [1] 3 4
# $`2`
# [1] 5 6
L <- lapply(split(rownum, (rownum-1) %/% 2), function(rn) mtcars[rn,])[1:3]
L
# $`0`
#               mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4
# $`1`
#                 mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Datsun 710     22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
# $`2`
#                    mpg cyl disp  hp drat   wt  qsec vs am gear carb
# Hornet Sportabout 18.7   8  360 175 3.15 3.44 17.02  0  0    3    2
# Valiant           18.1   6  225 105 2.76 3.46 20.22  1  0    3    1

Once you have a list where each element is a 2-row subset of the original frame, you can likely do something like

lapply(L, function(x) ...)

where ... is whatever you expect the your call to be.

A little shorter:

ret <- lapply(split(rownum, (rownum-1) %/% 2), function(rows) {
  if (length(rows) > 1) {
    mi.meld(mtcars[rn[1],], mtcars[rn[2],])
  }
})

})

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

Probably, something like this would help :

library(Amelia)
row_index <- seq(1, nrow(data), 2)
row_index <- row_index[row_index < nrow(data)]

result <- lapply(row_index, function(x) mi.meld(data[x,], data[x + 1,]))

Upvotes: 0

Related Questions