gpt4 book ai didi

r - 如何在 Power Query 中使用 R 转换步骤获取线性回归模型参数

转载 作者:行者123 更新时间:2023-12-01 11:11:19 25 4
gpt4 key购买 nike

假设我们有两个变量 Y 和 X,我们想在 Power Query 中使用 Transform > Run R script 建立一个简单的回归模型。这里有示例数据:

let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSAeJYnWglYyDLCMwyBbKMwSwLIMtEKTYWAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [Y = _t, X = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Y", Int64.Type}, {"X", Int64.Type}})
in
#"Changed Type"

然后我使用以下代码将 Run R script 步骤添加到 Power Query:

output <- lm(Y ~ X, data=dataset)

enter image description here

但是我得到一张空表:

enter image description here

如何修改R脚本获取模型摘要?

最佳答案

据我所知,为了从您的 R 脚本中检索任何输出,它必须采用 data.frame 的形式.但是,如果您尝试运行类似 df<-data.frame(output) 的程序, 你会得到错误

Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = > > stringsAsFactors) : cannot coerce class ‘"summary.lm"’ to a data.frame

但是您可以检索相同摘要的部分内容并将其组织到数据框中。在您的代码片段的基础上,以下是您如何为模型系数执行此操作。我冒昧地给你重命名了outputmodel .

代码:

model <- lm(Y ~ X, dataset)
df<- data.frame(coef(model))
names(df)[names(df)=="coef.model."] <- "coefficients"
df['variables'] <- row.names(df)

输出 1:

enter image description here

下一步,只需点击Table得到:

输出 2:

enter image description here

因为我没有你的数据,所以我只使用了 Enter Data这个简单的数据样本:

enter image description here

编辑:其他模型估计值

如果您想从模型中检索估计序列,例如残差或拟合值,只需将以下行添加到上面的代码片段中:

df_estimates <- data.frame(fitted(model), residuals(model))
colnames(df_estimates) <- c('fitted', 'residuals')

现在的初步输出是:

enter image description here

这是 Power BI 中一项非常实用的功能。只需点击 table在您要继续使用的数据框旁边。在后一种情况下,您将得到:

enter image description here

编辑 2 - 在输出中包含原始数据集:

#Y <- c(1,2,3,4,4)
#X <- c(1,2,3,4,5)

#dataset <- data.frame(X, Y)

model <- lm(Y ~ X, dataset)
df<- data.frame(coef(model))
names(df)[names(df)=="coef.model."] <- "coefficients"
df['variables'] <- row.names(df)
df_estimates <- data.frame(dataset$X, dataset$Y, fitted(model), residuals(model))
colnames(df_estimates) <- c('X', 'Y', 'fitted', 'residuals')
df_estimates

关于r - 如何在 Power Query 中使用 R 转换步骤获取线性回归模型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60059125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com