truncate1 <- function(x) {
qs <- quantile(x, c(.01, 0.99))
trimx <- x[x > qs[1] & x < qs[2]]
return(trimx)
}
TRU_BANK <- as.data.frame(BANK)
TRU_BANK$TVAR_AVG <- truncate1(TRU_BANK$TVAR_AVG)
Error in `$<-.data.frame`(`*tmp*`, "TVAR_AVG", value = c(19.6, 35.2, 26.9, :
replacement has 495 rows, data has 507
答案 0 :(得分:0)
修改函数以对数据帧进行子集化而不仅仅是字段;返回新数据集。可重复的东西:
df <- data.frame(y = c(1,2,3,4,5), z = c(1,2,3,4,5))
truncate1 <- function(df, x) {
qs <- quantile(df[ ,x], c(.01, 0.99))
trimx <- df[ df[ ,x] > qs[1] & df[ ,x] < qs[2], ]
return(trimx)
}
##putting the quotes around the column name or using a column number is key
new.df <- truncate1(df, "y")
new.df应为
new.df
y z
2 2 2
3 3 3
4 4 4