0

I have a dataframe column like this

> class(df$Released)
[1] "Date"

When I use apply over the vector, the value passed to FUN is coerced to character

> apply(df[1, ], 1, function(x) class(x['Released']))
          1 
"character"

What is going on?

cosmosa
  • 743
  • 1
  • 10
  • 23
  • 1
    You are telling it to apply across Rows (labelled 1 in the second argument of apply) and feeding it a single row, also 1 [df[1,] and then asking it the class of the column 'Released'...so this apply is only going to look at the very first instance of 'Released' because of how you defined the apply and function. run `str( on df$Released[1])` and see if it agrees with your character output.... – sconfluentus Oct 07 '17 at 18:50
  • also of interest https://stackoverflow.com/questions/18214431/r-apply-on-dataframe-how-to-avoid-implicit-character-conversion – user20650 Oct 07 '17 at 19:05
  • 1
    `df[1, ]` is still a data frame. `apply` coerces its `X` argument to a matrix when it is a data frame. So have a look at `as.matrix(df[1, ])` to see what happened. You could also read `help(apply)`. – Rich Scriven Oct 07 '17 at 19:08
  • @user20650 that is the answer I was looking for. This question is a duplicate. – cosmosa Oct 07 '17 at 19:42
  • okay, closed. cheers @cosmos1990 – user20650 Oct 07 '17 at 19:46

1 Answers1

2

Try this instead:

sapply(df, class)

The reason why:

Using apply() changes the data frame with as.matrix() before running the function class(), and in the process, all columns would return character. Meanwhile, using sapply() doesn't take that as.matrix() step since it's designed to work with vectors, so your classes will be shown accurately.

www
  • 4,124
  • 1
  • 11
  • 22