1

我正在尝试在 r 中为数据框循环这一系列步骤。这是我的数据:

ID  Height  Weight    
a   100  80    
b  80  90    
c  na  70    
d  120  na    
.... 

到目前为止,这是我的代码

winsorize2 <- function(x) {        
Min <- which(x == min(x))
Max <- which(x == max(x))
ord <- order(x)
x[Min] <- x[ord][length(Min)+1]
x[Max] <- x[ord][length(x)-length(Max)]
x}

df<-read.csv("data.csv")
df2 <- scale(df[,-1], center = TRUE, scale = TRUE)
id<-df$Type
full<-data.frame(id,df2) 
full[is.na(full)] <- 0
full[, -1] <- sapply(full[,-1], winsorize2)

我正在尝试做的是:-> 标准化数据帧,然后使用函数 winsorize2 对标准化数据帧进行 Winsorize,即将最极端的值替换为第二个最小的极值。然后重复 10 次。我如何为此做一个循环?我很困惑,因为我已经用 0 替换了 nas,所以我也应该从循环中删除这一步?

编辑:与@ekstroem 讨论后,我们决定改用代码来引入边界

df<-read.csv("data.csv")  
id<-df$Type  
df2<- scale(df[,-1], center = TRUE, scale = TRUE)  
df2[is.na(df2)] <- 0
df2[df2<=-3] = -3
df2[df2>=3] = 3

df3<-df2  #trying to loop again
df3<- scale(df3, center = TRUE, scale = TRUE)  
df3[is.na(df3)] <- 0  
df3[df3<=-3] = -3  
df3[df3>=3] = 3  
4

1 回答 1

1

有一些边界问题没有在您的代码中完全指定,但也许可以使用以下内容(使用基本 R 并且效率不高)

wins2 <- function(x, n=1) { 
    xx <- sort(unique(x)) 
    x[x<=xx[n]] <- xx[n+1]
    x[x>=xx[length(xx)-n]] <- xx[length(xx)-n]
    x 
}

这产生:

x <- 1:11
wins(x,1)
[1]  2  2  3  4  5  6  7  8  9 10 10
wins(x,3)
[1] 4 4 4 4 5 6 7 8 8 8 8
于 2016-08-07T18:29:10.990 回答