简体   繁体   中英

Nonlinear optimization for multiple groups on a data.frame in R

I need to optimize variables and find the minimum value of f , as previously asked and answered ( here ).

The difference is that I have a long data.frame, with several groups (IDs), and need to call optim() and store the results for each one of these groups.

Taking the example of the post , how could I elegantly adapt the R code to find solutions to each of my ID's in the data.frame "Measured" (one Y$par per ID of the data.frame)?

Thank you!

A <- c(0, 10, 20, 40, 32, 65, 78, 12)
B <- c(0, 1.51, 2.51, 4.32, 9.87, 5.33, 6.22, 4.86)
ID <-c("A", "A", "A", "A", "B", "B", "B", "B") 
Measured <- as.data.frame(cbind(A, B, ID))

I am not able to exactly reproduce your issue, since you do not include an example of how you would call the optim() function, but it seems to me that what you need is to split the dataframe by ID, and then use the lapply to call the same function on the sub-dataframe of each ID.

Here is an example, where I try to find the (A, B) values minimizing (AB)^2 for each ID. You real code will likely involve a call to optim() inside lapply().

A <- c(0, 10, 20, 40, 32, 65, 78, 12)
B <- c(0, 1.51, 2.51, 4.32, 9.87, 5.33,6.22, 4.86)
ID <-c("A","A","A","A","B","B","B","B") 
Measured <- as.data.frame(cbind(A, B, ID))

# Create a list containing one dataframe per ID
Measured2 <- split(Measured, f = Measured$ID)

# Apply a function to each dataframe in the list
# Let us assume we want to find the A, B pair minimizing (A - B)^2
results <- lapply(Measured2, function(df) {
  vals <- (A - B)^2
  df[which.min(vals), , drop = FALSE]
})

# Combined back to dataframe
do.call(rbind, results)
#>    A    B ID
#> A  0    0  A
#> B 32 9.87  B

Created on 2019-02-09 by the reprex package (v0.2.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM