Reputation: 109
I have a data frame and a vector identifying the rows I'm interested in:
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)
I also have two character vectors I would like to apply to the subset and specific columns.
startMonthV <- paste(c(" 1, ", substr(Sys.Date(), 1, 4)), collapse = "")
endMonthV <- paste(c(" 28, ", substr(Sys.Date(), 1, 4)), collapse = "")
I've tried using variations of the apply()
function with paste()
being the function I want to use, but to no avail. I would like my final result to be a data frame with all of the rows, but looking like this - the first two rows have been modified with the above startMonthV and 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
I'm new to R, and was wondering if the apply()
family would do, or using a function within the plyr package. Any stackoverflow answer I've found either applies to the whole data frame or collapses the data with the aggregate()
function.
Thank you.
Upvotes: 3
Views: 188
Reputation: 214927
We can use mapply
and assign the result back at the corresponding rows:
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
Here we created a vector days
according to the specific days you would like to append to the columns.
Upvotes: 1