Reputation: 1122
I have the following function to get the week from a given date
getWeek <- function (year, month, day) {
date <- as.Date(paste(year, month, day, sep = "-"), "%Y-%b-%d")
week <- format(date, "%W")
return(week)
}
I want to apply the above function to following data.frame x
and create a new column in x
. I tried using mapply
but it gives me NA
.
> dput(x)
structure(list(year = c(2003L, 2010L, 2012L, 2012L, 2007L), month = structure(c(3L,
10L, 9L, 8L, 6L), .Label = c(" Apr", " Aug", " Dec", " Feb",
" Jan", " Jul", " Jun", " Mar", " May", " Nov", " Oct", " Sep"
), class = "factor"), day = c(4L, 3L, 25L, 26L, 18L), Humidity = structure(c(38L,
71L, 73L, 49L, 87L), .Label = c("10", "100", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35",
"36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46",
"47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57",
"58", "59", "6", "60", "61", "62", "63", "64", "65", "66", "67",
"68", "69", "7", "70", "71", "72", "73", "74", "75", "76", "77",
"78", "79", "8", "80", "81", "82", "83", "84", "85", "86", "87",
"88", "89", "9", "90", "91", "92", "93", "94", "96", "97", "N/A"
), class = "factor")), .Names = c("year", "month", "day", "Humidity"
), row.names = c(2605L, 80763L, 108420L, 106512L, 54342L), class = "data.frame")
> mapply(getWeek, x$year, x$month, x$day)
[1] NA NA NA NA NA
I need getWeek
to be applied to each row in x
? Is mapply
the right one to use?
Upvotes: 1
Views: 134
Reputation: 823
Your getWeek
function is broken.
It should look something like this:
getWeek <- function (year, month, day) {
date <- as.Date(paste(year, month, day, sep = "-"), "%Y- %b-%d")
week <- format(date, "%W")
return(week)
}
You need to account for the leading space in your months.
Of course,
x$month <- substring(x$month,2)
would fix your issue as well.
Upvotes: 1
Reputation: 43245
Since your function is already vectorized, you don't need to use apply at all. Instead just call it with the correct variables (once you fix the error below, your mapply
solution will work as well):
with(x, getWeek(year, month, day))
However, you have a leading space before each month. So either you need to use the format string %Y- %b-%d' or remove it:
x$month <- gsub('^ ', '', x$month)`
Upvotes: 1