R:替换应用函数的数据框中的值,包括计算

时间:2017-11-21 12:11:49

标签: r

我目前正在努力解决以下问题:

我从雅虎财经下载了索引的每周数据。它正确地为每个星期一提取数据,但它将其称为星期日(即使是星期一的数据也很难)。

# a quick fix would just be:
SMI$Date <- SMI$Date+1

尽管如此,如果工作日是星期日而不是星期一,我想使用自动执行此功能的功能。

我尝试了以下方法,但它们都没有用。

# approach 1:
CheckDateYahoo1 <- function(datex){
for(i in length(datex)){
if(weekdays(datex[i])=="Sunday"){
datex[i] <- datex[i]+1
} else {
datex[i] <- datex[i]
}
}
}

应用此功能,没有任何反应。

# approach 2:
CheckDateYahoo2 <- function(datex){
if(weekdays(datex)=="Sunday"){
datex <- datex+1
}else{
datex <- datex
}
}

应用此功能,我收到以下警告信息:

Warning message:
In if (weekdays(datex) == "Sunday") { :
the condition has length > 1 and only the first element will be used

我认为我在函数代码中犯了一些明显的错误,因为我是R的新手 - 你可以帮我解决这个问题吗?

非常感谢提前

1 个答案:

答案 0 :(得分:1)

您的问题的解释

你不能return这些功能中的任何内容。即使你不需要在R函数中进行明确的return()调用(虽然我强烈推荐它),但你必须至少使用隐式返回。例如,比较

func1 <- function(x) {
    x <- x + 1
}

func2 <- function(x) {
    x <- x + 1
    x
}

func1(5)
# Nothing happens

func2(5)
# [1] 6

此外,在您的第二个功能中,您向if()提供与datex长度相同的逻辑向量,但它并未设计为这样做。例如,比较

if ( TRUE ) {
    print('yes')
}
# [1] "yes"

if ( c(FALSE, TRUE) ) {
    print('yes')
}
# Warning message:
# In if (c(FALSE, TRUE)) { :
#   the condition has length > 1 and only the first element will be used

解决方案

您可以尝试以下功能:

check_date <- function(dates) {
    dates[weekdays(dates) == 'Sunday'] <- dates[weekdays(dates) == 'Sunday'] + 1
    return(dates)
}

这似乎完成了你想要做的事情:

# Make some example data
dates <- as.Date(paste0('2017-11-', 1:7))
# Check the weekdays
weekdays(dates)
# [1] "Wednesday" "Thursday"  "Friday"    "Saturday"  "Sunday"    "Monday"   
# [7] "Tuesday" 
# And try our function
check_date(dates)
# [1] "2017-11-01" "2017-11-02" "2017-11-03" "2017-11-04" "2017-11-06" "2017-11-06"
# [7] "2017-11-07"
weekdays(check_date(dates))
# [1] "Wednesday" "Thursday"  "Friday"    "Saturday"  "Monday"    "Monday"   
# [7] "Tuesday"