2013-05-29 19 views
1

我有以下函数来获得每周指定日期的的R - 跨越每行应用于功能

getWeek <- function (year, month, day) { 
    date <- as.Date(paste(year, month, day, sep = "-"), "%Y-%b-%d") 
    week <- format(date, "%W") 
    return(week) 
} 

我想上面的功能适用于以下data.frame x并创建x新列。我尝试使用mapply,但它给我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 

我需要getWeekx被应用到每一行? mapply是否正确使用?

回答

1

由于你的函数已经被矢量化了,所以你根本不需要使用apply。而不是仅仅用正确的变量调用它(一旦你解决下面的错误,你的mapply解决方案也能发挥作用):

with(x, getWeek(year, month, day)) 

但是,你必须每个月前的前导空格。因此,您需要使用格式字符串%Y- %b-%d' or remove it: x $月< - gsub('^','',x $ month)`

1

您的getWeek功能已损坏。

它应该是这个样子:

getWeek <- function (year, month, day) { 
    date <- as.Date(paste(year, month, day, sep = "-"), "%Y- %b-%d") 
    week <- format(date, "%W") 
    return(week) 
} 

你需要考虑你月的主要空间。

当然,

x$month <- substring(x$month,2) 

将解决您的问题,以及。

+0

不得不挑选一个答案,我选择了最早的一个。 – Anand