0

I wish to do calculations on elements within columns. Starting in the first row until the last row. Doing this on several rows.

Here some sample date:

a <- data.frame(1.3, 1.4, 1.5, 1.6, 1.7, 1.8)
Y1 <- runif(100, 5.0, 17.5)
Y2 <- runif(100, 4.0, 27.5)
Y3 <- runif(100, 3.0, 14.5)
Y4 <- runif(100, 2.0, 12.5)
Y5 <- runif(100, 5.0, 17.5)
X <- runif(100, 5.0, 7.5)
df1 <- data.frame(X, Y1, Y2, Y3, Y4, Y5)

1) The calculation with the values should look like:

# For the first column: (x-a[1,1])^2
# For the second column: (x-a[1,2])^2
# For the third column: (x-a[1,3])^2
#And so on...

"x" stands for values from the column. The results (1 per row, so 100 in total) should be stored in a data frame.

2) If possible, the mean value of the results per column should be calculated as well, maybe combined with the code in step 1.

I ran this code but it did not work out. It does not create 100 values per column and the calculation is also wrong.

result1 <- as.data.frame(sapply(df1[1:6], function(x) mean((x-a[1:6])^2)))

Can anyone help me with this? I tried to fix it myself, but I still don't see the what is wrong.

Consti
  • 87
  • 2
  • 7
  • `lapply(Map(\`-\`, df1, a), \`^\`, 2)` ? – Frank Sep 19 '17 at 19:56
  • This works great, but how can I implement the "mean" argument? So that after calculating step one, the mean value of each column is calculated and only these mean values are stored in a data frame? – Consti Sep 19 '17 at 20:02
  • Hm, I'm not sure I follow. Something like `mapply(function(x,y) mean((x-y)^2), df1, a)` .. ? – Frank Sep 19 '17 at 20:06
  • 1
    Works fine, thank you! – Consti Sep 19 '17 at 20:10
  • Ok cool, glad it worked! I'll go ahead and close it, linking to a list of related functions (Map, mapply and others). – Frank Sep 19 '17 at 20:12

0 Answers0