我正在尝试在R中开发逻辑回归模型。我正在尝试循环遍历数据框(或tibble)的行,以便可以将该行中的列的子集乘以另一个向量作为点积。
我最初试图使用purrr的向量函数完成一些准备工作,但遇到了困难,决定在for循环中实现它。
这是我使用For-Loop的工作设计:
library(tidyverse)
# Define necessary functions
lambdaFunc <- function(factors,theta){
return((1+exp(sum(factors*theta)))^(-1))
}
# y is 0 or 1
# x and theta are a numeric vectors
indiv_likhd <- function(y,x,theta){
return(lambdaFunc(x,theta)^y*(1-lambdaFunc(x,theta))^(1-y))
}
# Assuming df is dataframe of the form
# Col1 Col2 ... ColN
# isDefault(0 or 1) factor1 ... factorN
likhds <- function(df,theta){
df <- as.data.frame(df)
likhds <- vector("numeric",nrow(df))
for (i in 1:nrow(df)) {
likhds[i] <- indiv_likhd(df[i,1],df[i,2:ncol(df)],theta)
}
return(likhds)
}所以
testdf <- tibble(y=c(1,0),x_1=c(1,1),x_2=c(1,1),x_3=c(1,1))
testTheta <- c(1,1,1)
likhds(testdf,testTheta)收益率
[1] 0.04742587 0.95257413有没有办法用向量函数来实现这一点--特别是purr包?这是我关于stackoverflow的第一个真正的问题,所以如果有什么遗漏或不清楚的地方,我道歉,在这种情况下,请让我知道。
谢谢。
发布于 2019-10-11 11:34:38
在不更改lambdaFunc和indiv_likhd的情况下,我们可以用pmap重写for循环
library(dplyr)
library(purrr)
testdf %>%
mutate(new_col = pmap_dbl(., ~indiv_likhd(c(...)[1], c(...)[-1], testTheta)))
# y x_1 x_2 x_3 new_col
# <dbl> <dbl> <dbl> <dbl> <dbl>
#1 1 1 1 1 0.0474
#2 0 1 1 1 0.953 c(...)用于捕获传递给pmap的所有值(这里是整行),因此c(...)[1]表示该行中的第一个值,c(...)[-1]表示该行中除第一个值之外的所有值。
发布于 2019-10-11 11:34:15
这里有一个选项
f <- function(df, theta) {
df %>%
group_by(y) %>%
nest() %>%
mutate(likhds = map2_dbl(y, data, function(y, x) indiv_likhd(y, x, theta))) %>%
pull(likhds)
}
f(testdf, testTheta)
#[1] 0.04742587 0.95257413说明:我们通过y来nest数据,然后使用map2_dbl遍历每一行的y和data对(这是您的x值),并将indiv_likhd的输出作为double向量返回。
https://stackoverflow.com/questions/58333791
复制相似问题