1
votes

The function enrollment. other does the following: (1) Takes in a data frame of 26 columns (2) Changes class of columns 1-2 to factor (3) Changes class of columns 3-26 to numeric (4) Creates column 27 as sum of columns 3-26 (5) Deletes all columns except 1 and 27 (6) Changes column name of 2nd column

  • If the data frame i am reading in is x, I want the second column name to be xENRL.

But when I call the function the following error appears:

z <- enrollment.other(OBC) Warning message: In colnames(x)[2] <- sprintf("%sENRL", name) : number of items to replace is not a multiple of replacement length

    enrollment.other <- function(x){
       x[, 1:2] <- as.data.frame(sapply(x[, 1:2], as.factor))
       x[, 3:26]<- as.data.frame(sapply(x[, 3:26], as.numeric))
       x[, 27] <- rowSums(x[, c(3:26)])
       x <- as.data.frame(x[, c(1, 27)])
       name <- deparse(substitute(x))
       colnames(x)[2] <- sprintf("%sENRL", name)
       as.data.frame(x)
    }
1

1 Answers

1
votes

We could use match.call

 enrollment.other <- function(x){
    x[1:2] <-  lapply(x[, 1:2], as.factor)
    x[3:26]<-  lapply(x[3:26], as.numeric)
    x[27] <- rowSums(x[3:26])
    x <-   x[c(1, 27)]
    name <- as.character(match.call()[[2]])
    colnames(x)[2] <- sprintf("%sENRL", name)
    x
 }

enrollment.other(d1)
#   V1 d1ENRL
#1   3    111
#2   3    117
#3   7     98
#4   5    118
#5   6    107
#6   9    109
#7   3    129
#8   7    124
#9   8    107
#10  3    130

Or if we need to use deparse(substitute

 enrollment.other <- function(x){
   name <- deparse(substitute(x))
   x[1:2] <-  lapply(x[, 1:2], as.factor)
   x[3:26]<-  lapply(x[3:26], as.numeric)
   x[27] <- rowSums(x[3:26])
   x <-   x[c(1, 27)]
   colnames(x)[2] <- sprintf("%sENRL", name)
  x
}

data

set.seed(24)
d1 <- as.data.frame(matrix(sample(1:9, 10*26, replace=TRUE), ncol=26))