0

I have multiple columns in a table called "Gr1","Gr2",...,"Gr10".

I want to convert the class from character to integer. I want to do it in a dynamic way, I'm trying this, but it doesn't work:

for (i in 1:10) {
  Col <- paste0('Students1$Gr',i)
  Col <- as.integer(Col)
                 }

My objective here is to know how to add dynamically the for variable to the name of a column. Something like:

for (i in 1:10) {
  Students1$Gr(i) <- as.integer(Students1$Gr(i))
                }

Any idea is welcome. Thank you very much, Matias

4
  • You want to change a table/matrix from character to integer? is it this what you want? your question is not so clear to me. Commented Jan 5, 2018 at 19:52
  • 1
    The best "R" way to do this would be with an *apply. Something like: cols <- names(Students)[grepl("Gr", names(Students))]; Students[, cols] <- lapply(Students[,cols], as.integer) Commented Jan 5, 2018 at 19:52
  • @MikeH.sapply might be better than lapply since we are not working with lists here. Commented Jan 5, 2018 at 19:54
  • @phil_t I believe we are working with lists. data.frames are lists with a few additional properties (see is.list(data.frame(a=1))). We are trying to replace list elements (the numeric vectors) with other elements (character vectors). sapply would work because it'll return a matrix, but then that has to be put back into list elements when you assign it to the data.frame. Also I dislike sapply because it simplifies the result for you. Commented Jan 5, 2018 at 20:18

1 Answer 1

1
# Example matrix
xm <- matrix(as.character(1:100), ncol = 10);
colnames(xm) <- paste0('Gr', 1:10);

# Example data frame
xd <- as.data.frame(xm, stringsAsFactors = FALSE);

# For matrices, this works
xm <- apply(X = xm, MARGIN = 2, FUN = as.integer);

# For data frames, this works
for (i in 1:10) {
    xd[ , paste0('Gr', i)] <- as.integer(xd[ , paste0('Gr', i)]);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.