将函数应用于数据框的子集但保留整个数据框

apply a function to a subset of a data frame but retain the whole data frame

我有一个数据框和一个标识我感兴趣的行的向量:

col1 <- c("June","June","June 11","June 11, 2012","June 14, 2012")
col2 <- c("September", "September", "October 8", "October", "Sept 27, 2012")
monthDF <- data.frame(cbind(col1, col2), stringsAsFactors = FALSE)
v0 <- c(1, 2)

我还有两个字符向量要应用于子集和特定列。

startMonthV <- paste(c(" 1, ", substr(Sys.Date(), 1, 4)), collapse = "")
endMonthV <- paste(c(" 28, ", substr(Sys.Date(), 1, 4)), collapse = "")

我尝试使用 apply() 函数的变体,paste() 是我想使用的函数,但无济于事。我希望我的最终结果是一个包含所有行的数据框,但看起来像这样 - 前两行已经用上面的 startMonthV 和 endMonthV 进行了修改:

           col1                 col2
1  June 1, 2016   September 28, 2016
2  June 1, 2016   September 28, 2016
3       June 11            October 8
4 June 11, 2012              October
5 June 14, 2012        Sept 27, 2012

我是 R 的新手,想知道 apply() 系列是否可以,或者使用 plyr 包中的函数。我发现的任何 Whosebug 答案要么适用于整个数据框,要么使用 aggregate() 函数折叠数据。

谢谢。

我们可以使用 mapply 并将结果分配回相应的行:

days <- c("1,", "28,")
monthDF[v0, ] <- mapply(paste, monthDF[v0, ], days, substr(Sys.Date(), 1, 4))
monthDF
           col1               col2
1  June 1, 2016 September 28, 2016
2  June 1, 2016 September 28, 2016
3       June 11          October 8
4 June 11, 2012            October
5 June 14, 2012      Sept 27, 2012

这里我们根据您要附加到列的特定日期创建了一个矢量 days