【发布时间】:2018-07-02 14:10:54
【问题描述】:
如何将整列作为参数传递给函数,然后创建一个新列作为其他两个函数的函数?例如,以this 为日期添加月份的出色功能,并以这个示例数据框为例:
df <- structure(
list(
date = structure(
c(
17135,
17105,
17105,
17074,
17286,
17317,
17317,
17347,
17105,
17317
),
class = "Date"
),
monthslater = c(10,
11, 13, 14, 3, 3, 3, 3, 4, NA)
),
.Names = c("date", "monthslater"),
row.names = c(NA, 10L),
class = "data.frame"
)
我想创建一个新列,在其中将列 date 和 monthslater 中的条目传递给函数 add.months 我原以为这样会起作用:
df$newdate <- add.months(df$date, df$monthslater)
但事实并非如此。
函数的完整代码是:
add.months <- function(date,n) seq(date, by = paste(n, "months"), length = 2)[2]
【问题讨论】:
-
我认为您的
add.months-function 没有正确添加月份。例如,在第 9 行中,newdate应该是 2 月 28 日,而add.months应该是 3 月 3 日。 -
@Jaap 很好发现!