0

All of my data comes in character format. When I try transforming a subset of the data in to numeric using apply it doesn't seem to work.

df2  <- as.data.frame(matrix(as.character(1:9),3,3))
df2[,-2]  <-  apply(df2[,-2], 2, as.numeric)
apply(df2, 2, class)

Could somebody point me out what I am doing wrong in the example above? Thanks

2
  • 3
    A matrix in R can only hold values of the same type. You cannot change some of the values to numeric and leave some others as characters. If you want different data types, you can use a data.frame, but even then, you can only have one data type per column. Commented Dec 19, 2014 at 22:56
  • Just df2 <- data.frame(df2,stringsAsFactors=F) after your first line. Commented Dec 19, 2014 at 22:58

1 Answer 1

1

As commented above.. a matrix in R can only hold values of the same type in all columns. You cannot change some of the values to numeric and leave some others as characters. If you want different data types, you can use a data.frame, but even then, you can only have one data type per column.

For your example case:

df2  <- as.data.frame(matrix(as.character(1:9),3,3))

will create a data.frame with factors in each column. If you want to convert the second column to numeric, you can do:

df2$V2 <- as.numeric(levels(df2$V2))[df2$V2]

Or

df$V2 <- as.numeric(as.character(df2$V2))

So you don't need to use apply in this case.

str(df2)
#'data.frame':  3 obs. of  3 variables:
# $ V1: Factor w/ 3 levels "1","2","3": 1 2 3
# $ V2: num  4 5 6
# $ V3: Factor w/ 3 levels "7","8","9": 1 2 3

If you wanted to convert all columns to numeric, you can do:

# if the columns were factors before:
df2[] <- lapply(df2, function(i) as.numeric(levels(i))[i])

Or

# if the columns were characters before:
df2[] <- lapply(df2, as.numeric)
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.