我是R.的新手。我已经找到了我的问题的答案,但没有找到任何对我有用的东西。
我有以下data.table:
data2 <- fread("file.txt", header = T, sep= "|", quote = "^" stringsAsFactors=FALSE);
Accounts_filed_date Incorporation_Date
2015-08-25 1863-05-01
2016-06-28 1863-07-16
2016-06-29 1863-12-29
2015-12-10 1880-08-17
Y <- function(incorporation_date, accounts_filled_date)
{timee <-Sys.Date()-incorporation_date;timee <- as.numeric(timee);
if(timee/365 <2){y=0; return(y)}
else{x <- as.Date(format(accounts_filled_date, "%2016-%m-%d"));
+ x <- Sys.Date()- x;
+ x <- as.numeric(x);
+ if(x<274) {y <-timee/365; return(pmax(pmin(y,5),0))}
+ else{y<-timee/365-1; return(pmax(pmin(y,5),0))}}}
data2[, c("Y") := Y(Incorporation_Date, Accounts_filed_date), with = FALSE]
但是,这不起作用,因为incorporation_date和accounts_filled_date是向量。
我尝试了ifelse,但使用以下代码:
Y <- function(incorporation_date, accounts_filled_date)
{timee <- Sys.Date()-incorporation_date;timee <- as.numeric(timee);
timee<- timee/365;
ifelse(timee<2,y=0,
x<-as.Date(format(accounts_filled_date, "%2016-%m-%d"));
x <-Sys.Date()- x;
x <- as.numeric(x);
ifelse(x<274,y <-timee, y<- timee-1));
return(pmax(pmin(y,5),0))}
返回以下内容:
Error: unexpected ';' in "Y <- function(incorporation_date, accounts_filled_date) {timee <- Sys.Date()-incorporation_date;timee <- as.numeric(timee); timee <- timee/365;ifelse(timee<2,y=0,x
基本上,我的问题是: 如何在ifelse语句的“false”部分中包含多个操作?
更新
Y <- function(incorporation_date, accounts_filled_date)
{timee <- Sys.Date()-incorporation_date;timee <- as.numeric(timee);
timee2<- timee/365;
timee2 <- as.integer(timee2);
x<-as.Date(format(accounts_filled_date, "%2016-%m-%d"));
x <- Sys.Date()- x;
x <- as.numeric(x);
ifelse**(timee2 <= 2,** y<-0, ifelse(x<274,y <-timee2, y<- timee2-1));
return(pmax(pmin(y,100),0))}
除了时间&lt; = 2,bit之外,这是有效的。我已经双重检查 - 它返回的值小于2,只是逻辑返回FALSE。有什么建议吗?
答案 0 :(得分:0)
重新安排语句捕获逻辑:
Y <- function(incorporation_date, accounts_filed_date)
{timee <- Sys.Date()-incorporation_date;timee <- as.numeric(timee);
timee2<- timee/365;
x<-as.Date(format(accounts_filed_date, "%2016-%m-%d"));
x <- Sys.Date()- x;
x <- as.numeric(x);
y <- ifelse(timee2 <= 2, 0,ifelse(x < 274, timee2, timee2-1));
return(pmax(pmin(y,5),0))}