首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将值添加到数据帧的每一行,给定列名称的向量。

将值添加到数据帧的每一行,给定列名称的向量。
EN

Stack Overflow用户
提问于 2019-05-19 12:52:40
回答 1查看 52关注 0票数 1

我正在为一个分类模型列表编写我的predict函数,所以每个模型都会投票支持一些预测。

我创建了以下函数,但速度非常慢。最内部的for循环需要很长的时间来计算。

代码语言:javascript
运行
复制
predict.risemble <- function(.models, .dataset) {
  all_levels <- unique(unlist(lapply(.models, function(x) x$levels)))
  voting_df <- data.frame(matrix(0, ncol = length(all_levels), nrow = nrow(.dataset)))
  colnames(voting_df) <- all_levels
  voting_df <- as_tibble(voting_df)
  for (model in .models) {
    cat(sprintf("Making predictions for model %s\n", model$method))
    predictions <- predict(model, .dataset)
    cat("Voting ...\n")
    for (i in 1:length(predictions)) {
      prediction <- as.character(predictions[i])
      voting_df[i, prediction] <- voting_df[i, prediction] + model$results$Kappa
      if (mod(i, 1000) == 0) {
        cat(sprintf("%f%%\n", i / length(predictions) * 100))
      }
    }
  }
  return (as.factor(colnames(voting_df)[apply(voting_df, 1, which.max)]))
}

我需要加快内部最for循环。

因此,给定一个预测向量(类factor),我们可以使用as.character将其转换为列的名称(类character)。让我们把这个向量称为predictions

我需要向voting_df的每一行添加一些特定值,给出列predictions的向量。

示例:

代码语言:javascript
运行
复制
predictions <- c("a", "a", "a", "b", "c")
代码语言:javascript
运行
复制
> voting_df
# A tibble: 5 x 3
      a     b     c
  <dbl> <dbl> <dbl>
1     1     0     0
2     1     0     0
3     1     0     0
4     0     1     0
5     0     0     1

编辑我的predict函数的最终版本是:

代码语言:javascript
运行
复制
predict.risemble <- function(.models, .dataset) {
  all_levels <- unique(unlist(lapply(.models, function(x) x$levels)))
  voting_df <- data.frame(matrix(0, ncol = length(all_levels), nrow = nrow(.dataset)))
  colnames(voting_df) <- all_levels
  voting_df <- as_tibble(voting_df)
  voting_df <- voting_df %>% select(noquote(order(colnames(voting_df))))
  for (model in .models) {
    predictions <- as.character(predict(model, .dataset))
    votes <- tibble(prediction = predictions) %>%
      mutate(prediction_id = row_number(), value = model$results$Kappa) %>%
      spread(prediction, value) %>%
      select(-one_of("prediction_id"))
    votes[, all_levels[!all_levels %in% names(votes)]] <- NA
    votes <- votes %>% select(noquote(order(colnames(votes))))
    votes[is.na(votes)] <- 0
    voting_df <- voting_df + votes
  }
  return (as.factor(colnames(voting_df)[apply(voting_df, 1, which.max)]))
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-19 13:01:12

我将尝试从您的向量构建一个数据格式,然后使用tidyrs扩展函数:

代码语言:javascript
运行
复制
library(tidyverse)
tibble(pred =predictions) %>%
mutate(pred_id = row_number(), value =1) %>%
spread(pred, value)

那就用零代替NAs。这能达到你的目的吗?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56208012

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档