问题描述:

d_date <- "23-10-2015"

mypreibnr(d_date)

And myibnr returns yq only.

The above code gives me the output

"2015-16 Q3"

I've presented the code below for a range of rows. I get an error highlighting the paste0 rows in the function myibnr.

I'm returning the financial year for a given date. ibnr_data[,7] is the required date column and ibnr_data[i,8] is the required output column.

i=1

while(i<=nrow(ibnr_data)){

d_date <- ibnr_data[i,7]

mypreibnr(d_date)

i <- i+1

}

mypreibnr <- function(d_temp){

temp <- dmy(d_temp) # passed as t in myibnr(a,t)

b <- substr(year(temp),4,4)

myibnr(b,temp)

myibnr <- function(a, t){

temp1 <- dmy(str_replace("01-04-201x","x",a))

temp2 <- dmy(str_replace("30-06-201x","x",a))

temp3 <- dmy(str_replace("01-07-201x","x",a))

temp4 <- dmy(str_replace("30-09-201x","x",a))

temp5 <- dmy(str_replace("01-10-201x","x",a))

temp6 <- dmy(str_replace("31-12-201x","x",a))

temp7 <- dmy(str_replace("01-01-201x","x",a))

temp8 <- dmy(str_replace("31-03-201x","x",a))

yyy <- substr(t,1,3)

ay <- as.numeric(a)

ay_0 <- ay-1

ay_1 <- ay+1

qt <- which(unlist(list(between(t,temp1,temp2),between(t,temp3,temp4),between(t,temp5,temp6),between(t,temp7,temp8))))

if(qt<=3){

yq <- paste0(yyy,ay,"-",yyy,ay_1," Q",qt,sep="")

} else {

yq <- paste0(yyy,ay_0,"-",yyy,ay," Q",qt,sep="")

}

ibnr_data[i,8] <- yq

}

网友答案:

Three problems with your code:

  1. You never closed the first function, mypreibnr; add a }.

  2. Though this is technique/style only, your indentation is inconsistent and non-standard; consider using RStudio, ESS, or something else that automates indentation for you. This would likely have helped with #1.

  3. You incorrectly assume that your last line, ibnr_data[i,8] <- yq will know to return all of ibnr_data.

For the last (the culprit), realize that assignment to a variable in R invisibly returns the value actually assigned. This allows chaining of assignment, so that

x <- y <- 5

assigns the value 5 to both x and y. This is equivalent to

x <- (y <- 5)

highlighting the fact that the assignment of 5 to y is done first, it silently returns a 5, which is then assigned to x (and invisibly returned). If you apply this logic to your code, you will see that

obnr_data[i,8] <- yq

is assigning the value of yq (a single string) to a member of the vector ibnr_data. So it is the single string (yq) that is invisibly returned by the assignment, not the contents of the entire vector. (Had you made an assignment of a vector of strings, then that would have been invisibly returned.)

Perhaps adding ibnr_data after the assignment will do what you need?

相关阅读:
Top