【问题标题】:List as input of a function列表作为函数的输入
【发布时间】:2014-02-26 08:55:01
【问题描述】:

我(作为 R 的初学者)正在尝试将数据帧列表作为函数的输入传递,以将某些变量从 char 更改为日期。当我运行脚本时,它可以工作。如果我在一个函数中尝试它,我不会收到任何错误,但变量的类型仍然是一个字符。您可以在下面找到该功能。提前感谢您的建议。

data <- list(complaints,credit,customers,delivery,subscriptions,formula)

building <- function(x){
for (i in 1:6){
vars <- which(names(x[[i]]) %in% c("StartDate","EndDate","PaymentDate","RenewalDate","ProcessingDate","ComplaintDate","DOB"))

x[[i]][,vars] <- sapply(vars,function(vars) as.Date(x[[i]][,vars],format=f),simplify=FALSE)
}

complaints <- x[[1]]

credit <- x[[2]]

customers <- x[[3]]

delivery <- x[[4]]

subscriptions <- x[[5]]

formula <- x[[6]]
}

building(data)

【问题讨论】:

  • 你必须返回你的固定数据,例如data2
  • 如果您提供可重现的示例并告诉我们您想要的输出是什么,我们可能会做得更多。有关如何提供封装数据的信息,请参阅stackoverflow.com/questions/5963269/…

标签: r list function


【解决方案1】:

您正在尝试修改函数中在函数之外定义的对象。这在计算机科学中称为副作用:http://en.wikipedia.org/wiki/Side_effect_%28computer_science%29

你不能在 R 中这样做。

相反,您可以这样做:

data <- list(complaints,credit,customers,delivery,subscriptions,formula)

building <- function(x){
for (i in 1:6){
vars <- which(names(x[[i]]) %in% c("StartDate","EndDate","PaymentDate","RenewalDate","ProcessingDate","ComplaintDate","DOB"))

x[[i]][,vars] <- sapply(vars,function(vars) as.Date(x[[i]][,vars],format=f),simplify=FALSE)
}

return(x)
}

output <- building(data)

complaints <- output [[1]]

credit <- output [[2]]

customers <- output [[3]]

delivery <- output [[4]]

subscriptions <- output [[5]]

formula <- output [[6]]

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多