2

変数 x3 を、他の 2 つの変数 X1 と X2 を考慮して計算された各クラスターに対応する平均値で代入したいと考えています。「平均」のように、Hmiscパッケージから代入する関数を渡すことができ、それが機能することを私は知っています。したがって、次のすべてを行う関数を渡したいと思います。

私はそうするためにコードを書くのに使用します:

df1 <- data.frame(x1=runif(1000,0,100),
                  x2=runif(1000,0,100),
                  x3=c(runif(900,0,100),rep(NA,100)))

このすべてを行う関数を渡したい:

clust<-kmeans(df1[,-grep('x3', colnames(df1))], 3)
df1$clust<-clust$cluster

library(plyr)
cc<-ddply(df1, 'clust',summarise, mean=mean(x3, na.rm=TRUE))

df2<-merge(df1,cc, by='clust')
df2$x3imputed2<-ifelse(is.na(df2$x3),df2$mean, df2$x3)

このすべてのコードを関数として渡し、Hmisc で使用する方法はありますか? (変数として x3 を導入する ddply に問題がありました)。

次のようなもの:

ff<-function(i) {
clust<-kmeans(df1[,-grep(i, colnames(df1))], 3)
df1$clust<-clust$cluster
cc<-aggregate(df1[,i], by=list(clust=df1$clust), "mean", na.rm=TRUE)
df2<-merge(df1,cc, by='clust')
df2$x3imputed2<-ifelse(is.na(df2[, i]),df2$x, df2[,i])
}


f1$imputedx3<-with(df1, impute(x3,ff))

しかし、私はエラーが発生します:

空のクラスター: 初期中心のより良いセットを試してください

x3 に置き換えても、同じエラーは発生しません。

4

1 に答える 1

4

試す

library(lazyeval)
library(dplyr)
f1 <- function(dat, cname){
    #get the third argument i.e, 'cname'
    nm1 <- match.call()[[3]]
    #paste 'imputed' for renaming the new column later
    nm2 <- paste0(nm1, 'imputed')
    #create an numeric column index that will be removed in kmeans calc
    indx <- grep(cname, colnames(dat))
    #get the 'kmeans' of the columns other than the 'cname'
    clust <- kmeans(dat[,-indx],3)$cluster
    #group by 'clust' and create new column with 'mutate'
    dat %>%
       group_by(clust=clust) %>%
       mutate_(interp(~ifelse(is.na(v), mean(v, na.rm=TRUE), v),
                      v=as.name(cname))) %>% 
       #rename the column 
       setNames(., c(head(names(.),-1), nm2))     
   }

 f1(df1, 'x3')

または、引用符なしで渡すこともできますv= lazy(cname)

 f2 <- function(dat, cname){
   nm1 <- match.call()[[3]]
   nm2 <- paste0(nm1, 'imputed')
   indx <- grep(nm1, colnames(dat))
   clust <- kmeans(dat[,-indx],3)$cluster
   dat %>%
      group_by(clust=clust) %>%
      mutate_(interp(~ifelse(is.na(v), mean(v, na.rm=TRUE), v), 
      v= lazy(cname))) %>%
     setNames(., c(head(names(.),-1), nm2))  
   }

  f2(df1, x3)
于 2015-07-26T20:21:11.403 に答える