Angelina Zapolska
Angelina Zapolska

Reputation: 11

Iterate over multiple dataframe columns at the same time in R

I have 3 dataframes (x,y,z) in R with 541 columns and around 14 000 rows each. I have to apply a CDFt function on them, which works with single lists. Application for the first column looks like:

result <- CDFt(x$v1, y$v1, z$v1, npas = round(3*1000/4))

This function takes all 14000 values from the first column of each dataframe. What I want to do is to loop through each of 541 columns in three dataframes simultaneously, where the function is applied to first, second, ... etc. column of all three dataframes. The for loop:

for (i in x)
   for (j in y)
       for (k in z)

would give us 541541541 number of outputs, while I only want 541 of them.

Could anyone help me with that?

Upvotes: 1

Views: 687

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

Maybe you can try Map like below

Map(CDFt,x, y, z, list(npas = round(3*1000/4)))

Upvotes: 0

Gregor Thomas
Gregor Thomas

Reputation: 145755

You only want one loop.

result = list()
for (i in 1:ncol(x)) {
  result[[i]] = CDFt(x[[i]], y[[i]], z[[i]], npas = round(3*1000/4))
}

Upvotes: 1

Related Questions