I have a dataframe called Profile_1_2 of data that is formatted like this:
| Profile_number | chl_z | Cphyto_z |
|---|---|---|
| 1 | 0.2 | 10 |
| 1 | 0.6 | 100 |
| 2 | 0.1 | 20 |
| 2 | 0.5 | 90 |
Profile_number denotes a group, each profile contains 200 rows. I implemented a model from a python script using reticulate
for (i in c("tidyverse","reticulate")) {
if (!require(i, character.only = TRUE)) {
install.packages(i, dependencies = TRUE)
library(i, character.only = TRUE)}}
np <- import("numpy")
source_python('cbpm_argo.py')
cbmp_argo is function with input of 5 variables:
def cbpm_argo(chl_z,Cphyto_z,irr,dayOfYear,lat):
and output of 7:
return pp_z,mu_z,par_z,prcnt_z,nutTempFunc_z,IgFunc_z,mzeu
when I use the function in a profile-wise basis it outputs a list of 7 elements without naming them:
Profile_1 <- Profile_1_2 %>%
filter(Profile_number == 1)
output <- cbpm_argo(Profile_1$chl_z,Profile_1$Cphyto_z,30,113,30)
summary(output)
Length Class Mode
[1,] 200 -none- numeric
[2,] 200 -none- numeric
[3,] 200 -none- numeric
[4,] 200 -none- numeric
[5,] 200 -none- numeric
[6,] 200 -none- numeric
[7,] 1 -none- numeric
I want the model output to be added to the initial dataframe as additional columns, which I have done simply using square brackets, resulting in a dataframe with 9 columns as intended:
Profile_1_2 <- Profile_1_2 %>%
mutate(.by = Profile_number,
pp_z = cbpm_argo(chl_z,Cphyto_z,30,113,30)[[1]],
mu_z = cbpm_argo(chl_z,Cphyto_z,30,113,30)[[2]],
par_z = cbpm_argo(chl_z,Cphyto_z,30,113,30)[[3]],
prcnt_z = cbpm_argo(chl_z,Cphyto_z,30,113,30)[[4]],
nutTempFunc_z = cbpm_argo(chl_z,Cphyto_z,30,113,30)[[5]],
IgFunc_z = cbpm_argo(chl_z,Cphyto_z,30,113,30)[[6]],
mzeu = cbpm_argo(chl_z,Cphyto_z,30,113,30)[[7]]
)
However this seems incredibly long winded and (I think) requires repeated use of the function for a single profile. Is there a more concise way of extracting the model output into the dataframe.
for those interested I am using a slightly altered version of the scripts listed by Lionel Arteaga https://zenodo.org/records/6599224#23.YqJZFC1h3uM