我有一个<?= Html::a('<span class="glyphicon glyphicon-floppy-disk"></span> Save', ['simpan'], ['class' => 'btn btn-primary']) ?>
的{{1}},其中每个表具有相同的行数但具有不同的列数。对于每个public function actionSimpan()
{
$model = new Armada();
if ($model->load(Yii::$app->request->post())) {
// get the instance of the uploaded file
$imageName = $model->NAMA_ARMADA;
$model->photo = UploadedFile::getInstance($model,'photo');
$model->photo->saveAs('uploads/'.$imageName.'.'.$model->photo->extension);
//save the path in the column
$model->IMG_ARMADA = 'uploads/'.$imageName.'.'.$model->photo->extension;
$model->save();
return $this->redirect(['index']);
}
return $this->render('create', [
'model' => $model,
]);
}
,我正在计算每列的平均值,然后将其乘以该列的总和。
这给我Html::submitInput
中每个list
的新行(每个tables
中每一列的一个值)。然后,我需要对每个新行的值求和,然后将其除以列值的总和。我可以这样:
table
它可以工作,但是我想知道是否有更好的方法可以做到这一点?
答案 0 :(得分:1)
您可以还原为tidyverse
:
library(tidyverse)
list_of_tables <- list(mtcars, ChickWeight %>% mutate_all(as.numeric))
## loop through all tables
(ret <- map_dbl(list_of_tables,
## for each table calculate your statistic on numeric columns
~ .x %>%
summarise_all(~ mean(.x) * sum(.x)) %>%
## transform to long format
gather(column, value) %>%
## summarise the results
summarise(result = sum(value) / sum(.x)) %>%
## return the result as vector
pull(result)
))
# [1] 173.41411 97.18084
结果可能不会更好,但可以肯定地更具可读性,这是学习tidyverse
(恕我直言)的语法的最佳时机。
这确实与您的代码相同:
LIST.OF.TABLES <- list_of_tables
es <- lapply(LIST.OF.TABLES, function(x){apply(x,2,myfun)})
sapply((es), sum)/sapply(LIST.OF.TABLES, sum)
# [1] 173.41411 97.18084