zhaoyi
zhaoyi

Reputation: 15

Function Creation in R

How do I turn this in a function?

X is a var and Z are the different datasets

X<-as.factor(X)
niveis<-levels(X)
teste<-table(X)

for(i in 1:length(niveis)) {
Z$weight[X == niveis[i]] <- teste[niveis[i]]
                       }

Z$weight<-as.numeric(Z$weight)

I've been trying:

weight_function<-function(Z, X) {

  X<-as.factor(X)
  niveis<-levels(X)
  teste<-table(X)

for(i in 1:length(niveis)) {
  Z$weight[X == niveis[i]] <- teste[niveis[i]]
                           }
  Z$weight<-as.numeric(Z$weight)

}

But nothing happens and no error is shown

Upvotes: 0

Views: 40

Answers (1)

John Coleman
John Coleman

Reputation: 51998

R functions don't (normally) work by side effects. Your function returns nothing. It mutates its local copy of Z but then discards the changes. Instead, return the mutated copy:

weight_function<-function(Z, X) {

  X<-as.factor(X)
  niveis<-levels(X)
  teste<-table(X)

  for(i in 1:length(niveis)) {
    Z$weight[X == niveis[i]] <- teste[niveis[i]]
  }
  Z$weight<-as.numeric(Z$weight)
  Z
}

Then call it like Z <- weight_function(Z, X)

Upvotes: 1

Related Questions