1

我有一个执行一些条件检查并输出“日期”对象的函数。“s”类是“日期”。但是“mapply”的输出是一个数字向量。我希望输出“dataF1$RECENCY”也是一个日期对象。在这方面需要帮助

dataF1 = read.csv("C:\\Users\\DATA.csv", header = TRUE, sep = ",")
dataF1$DT = as.Date(dataF1$DT, format = "%d-%b-%y")

myFunction <- function(x, y, z){
    if (x == "U"){
        s = z + 60
    }
    else {
        if (y == "ANNUAL"){
            s = z + 30
        }
        else {
            s = z + 15
        }
    }
    print (s)
    print (class(s))
    return(s)
}

dataF1$RECENCY = mapply(myFunction, x = dataF1$TYPE, y = dataF1$PAYMENT, z = dataF1$DT)

> head(dataF1$RECENCY)
[1] 13966 14340 14467 13752 13721 13752
4

1 回答 1

2

不允许mapply简化您的结果。

> mapply(function(x) {as.Date(x, format = "%m.%d.%Y")}, x = "1.5.2014", SIMPLIFY = FALSE)
$`1.5.2014`
[1] "2014-01-05"

> mapply(function(x) {as.Date(x, format = "%m.%d.%Y")}, x = "1.5.2014", SIMPLIFY = TRUE)
1.5.2014 
   16075

您可以使用do.call.

out <- mapply(function(x) {as.Date(x, format = "%m.%d.%Y")}, x = c("1.5.2014", "2.5.2014"), SIMPLIFY = FALSE)
do.call("c", out)
    1.5.2014     2.5.2014 
"2014-01-05" "2014-02-05"
于 2014-01-05T14:51:41.043 回答