我在重载构造函数时遇到问题,它不会让我告诉它变量包含什么类型。我怎么能强迫一个类型,或者无论如何都要做这个工作......?
calc_readmit <- function(df) {
if (nrow(df) == 1) return(NA)
admitted <- c(0,cumsum(df$Index_admission))
admitted <- admitted[-length(admitted)]
dt1 <- df$dish_date[min(which(admitted > 0))-1]
admit2 <- ifelse(admitted > 0, dt1, NA)
time <- as.integer(df$adm_date) - admit2
as.integer(ifelse(admitted > 0, time, NA))
}
library(data.table)
df <- data.table(df, key= "id")
df <- df[, time_to_readmission := calc_readmit(.SD), by= "id"]
R> df
id Index_admission. adm_date dish_date time_to_readmission
1: 1243 TRUE 2009-02-05 2009-02-08 NA
2: 1243 TRUE 2011-02-05 2011-02-19 727
3: 1244 FALSE 2009-02-07 2009-02-08 NA
4: 1244 TRUE 2009-03-05 2009-03-15 NA
5: 1244 FALSE 2011-04-05 2011-04-07 751
6: 1244 FALSE 2012-03-25 2012-03-27 1106
7: 1244 TRUE 2012-05-05 2012-05-20 1147
8: 1244 TRUE 2013-09-08 2013-09-15 1638
9: 1244 FALSE 2014-01-05 2014-01-15 1757
10: 2333 FALSE 2010-01-01 2010-01-08 NA
11: 2333 FALSE 2011-01-01 2011-01-05 NA
12: 2333 TRUE 2011-02-02 2011-02-25 NA
13: 2333 FALSE 2012-01-25 2012-01-28 334
14: 5422 TRUE 2015-03-05 2015-03-15 NA
答案 0 :(得分:3)
我怎样才能强制使用某种类型,或者让它继续工作......
使用类型断言:
// If first is Point all must be Points
let points = pointsOrWalls as Point[];
完成:
class Wall {w}
class Point {p}
class Foo {
walls;
name
constructor(points: Point[], name?: string);
constructor(walls: Wall[], name?: string);
constructor(pointsOrWalls: (Wall | Point)[], name?: string) {
if (pointsOrWalls[0] instanceof Point) {
// If first is Point all must be Points
let points = pointsOrWalls as Point[];
// But here typescript says that pointsOrWalls is of type (Wall | Point)[]
this.walls = points.map(function(point, ind, points) {
return new Wall(point, points[++ind % points.length])
})
}else{
// Since these aren't points they are Walls
this.walls = walls
}
this.name = name
}
}
https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html