I think that the title explains mostly what I am trying to do. As I am not so experienced with the loop I will need your help.
The data which I have:
> dput(data)
structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 778936.666666667,
0, 0, 0, 0, 2478666.66666667, 2255834.16666667, 0, 1797065.41666667,
0, 0, 8091450, 10536461.5079365, 0, 2325600, 0, 0, 0, 1011700,
2049325, 870025, 0, 0, 0, 892385, 3216538.33333333, 960480, 1024325,
0, 0, 557780, 5798938.88888889, 846266.666666667, 1183267.5,
0, 0, 1126786.66666667, 7603630.47619048, 888885, 1771708.33333333,
0, 0, 1557738.33333333, 5441300, 0, 2007712.33333333, 0, 0, 1792833.33333333,
3435203.33333333, 1913650, 3339118.93939394, 0, 0, 1047475, 2194228.33333333,
1248360, 973797.916666667, 671265, 0, 804250, 0, 0, 0, 0, 0,
0, 1788100, 1746900, 2140050, 2584000, 0, 947850, 0, 462237.5,
639437.666666667, 636732.333333333, 0, 0, 0, 508568.333333333,
1397257.5, 1016524.58333333, 0, 0, 0, 270466.666666667, 742731.785714286,
408040.681818182, 0, 0, 0, 316706.666666667, 714654.722222222,
592564.294871795, 0, 0, 0, 255310, 434271.5, 590129.537037037,
0, 0, 0, 617560, 227435, 367492.5, 0, 0), .Dim = c(6L, 20L), .Dimnames = list(
c("Greg", "Tommy", "Seb", "Martin", "Alesa", "Yuri"), c("January",
"February", "March", "April", "May", "June", "July", "August",
"September", "October", "January2", "February2", "March2",
"April2", "May2", "June2", "July2", "August2", "September2",
"October2")))
The vector which is needed for the function:
> dput(vec_list)
c(10L, 34L, 59L, 84L, 110L, 134L, 165L, 199L, 234L, 257L, 362L,
433L, 506L, 581L, 652L, 733L, 818L, 896L, 972L, 1039L)
Now the function which I would like to apply to whole data (is much bigger than the given example):
work_func <- function(i) data[1,] <- AIC(lm(vec_list~poly(data[1,],i, raw=TRUE)))
as.integer(optimize(work_func,interval = c(1,length(data[1,])-1))$minimum)
That's just for a single row. The results of each row should be just a simple number which I would like to put to the new column or just store it as a vector...
Use apply() function when you wanted to update every row in pandas DataFrame by calling a custom function. In order to apply a function to every row, you should use axis=1 param to apply(). By applying a function to each row, we can create a new column by using the values from the row, updating the row e.t.c.
As @Colonel correctly noted, you can use apply
with a margin of 1 here
My_func <- function(x) {
work_func <- function(i) AIC(lm(vec_list ~ poly(x, i, raw = TRUE)))
as.integer(optimize(work_func, interval = c(1, length(x) - 1))$minimum)
}
apply(data, 1, My_func)
# Greg Tommy Seb Martin Alesa Yuri
# 2 12 12 6 18 18
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With