gpt4 book ai didi

function - 如何使 R 函数返回多列并将它们 append 到数据框中?

转载 作者:行者123 更新时间:2023-12-04 16:50:04 26 4
gpt4 key购买 nike

从此数据框开始

myDF = structure(list(Value = c(-2, -1, 0, 1, 2)), .Names = "Value", row.names = c(NA, 5L), class = "data.frame")

假设我想在 myDF$Value 的每一行上运行这个函数
getNumberInfo <- function(x) {
if(x %% 2 ==0) evenness = "Even" else evenness="Odd"
if(x > 0) positivity = "Positive" else positivity = "NonPositive"
if (positivity == "Positive") logX = log(x) else logX=NA
c(evenness,positivity,logX)
}

...获取此数据框
structure(list(Value = c(-2, -1, 0, 1, 2), Evenness = c("Even", 
"Odd", "Even", "Odd", "Even"), Positivity = c("NonPositive",
"NonPositive", "NonPositive", "Positive", "Positive"), Log = c(NA,
NA, NA, "0", "0.693147180559945")), row.names = c(NA, 5L), .Names = c("Value",
"Evenness", "Positivity", "Log"), class = "data.frame")

最佳答案

您可能想更改您的 getNumberInfo函数返回一个列表而不是一个向量,这样值可以有不同的类型。实际上,它们都被转换为字符串,这可能不是您想要的 logX .

getNumberInfo <- function(x) {
if(x %% 2 ==0) evenness = "Even" else evenness="Odd"
if(x > 0) positivity = "Positive" else positivity = "NonPositive"
if (positivity == "Positive") logX = log(x) else logX=NA
list(evenness,positivity,logX)
}

此外,您可以使用名称以获得更好的效果,这样您就不必重复它们:
getNumberInfo <- function(x) {
list(evenness = if(x %% 2 ==0) "Even" else "Odd",
positivity = if(x > 0) "Positive" else "NonPositive",
logX = if(x > 0) log(x) else NA)
}

那么解决方案就变得简单了:
> cbind(myDF, t(sapply(myDF$Value, getNumberInfo)))
Value evenness positivity logX
1 -2 Even NonPositive NA
2 -1 Odd NonPositive NA
3 0 Even NonPositive NA
4 1 Odd Positive 0
5 2 Even Positive 0.6931472

最后,如果你使用 ifelse (可以处理向量)而不是 if ,它变得更加简单,因为您不必调用 apply :
getNumberInfo <- function(x) {
list(evenness = ifelse(x %% 2 ==0, "Even", "Odd"),
positivity = ifelse(x > 0, "Positive", "NonPositive"),
logX = ifelse(x > 0, log(x), NA))
}

> cbind(myDF, getNumberInfo(myDF$Value))
Value evenness positivity logX
1 -2 Even NonPositive NA
2 -1 Odd NonPositive NA
3 0 Even NonPositive NA
4 1 Odd Positive 0.0000000
5 2 Even Positive 0.6931472

最后一个解决方案会发出警告,因为它实际上正在计算每个元素的日志,而不仅仅是那些带有 x>0 的元素的日志。 .不确定处理这个问题的最优雅的方法。

关于function - 如何使 R 函数返回多列并将它们 append 到数据框中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1395156/

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