0

lets say I have a dataframe data with numeric column col

is_class <- function(x){
    return(class(x['col']))
}
data['class'] <- apply(data, 1, is_class)

should, to my understanding be equivalent to:

data['class2'] <- class(data$col)

However.

all(data['class'] == 'character') is TRUE

all(data['class2'] == 'numeric') is TRUE

It appears that apply() converts each row to all characters. Which makes then performing any numeric operation very difficult.

as below:

times_two <- function(x){
    return(x['col']*2)
}
data['col2'] <- apply(data, 1, times_two)

Error in x["col"] * 2: non-numeric argument to binary operator
Traceback:

returns

1. apply(data, 1, times_two)
2. FUN(newX[, i], ...)
Harvs
  • 503
  • 1
  • 6
  • 18
  • Ah, yes, that seems reasonable. – AkselA Sep 24 '19 at 15:20
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Sep 24 '19 at 15:24
  • 1
    What do you want to achieve? To get the class of a specific column, just `class(data[["columnName"]])` is enough. If you want to know the class of each column, just try `lapply(data,class)`. Also, you should rarely use `apply` on `data.frame`s. – nicola Sep 24 '19 at 15:25
  • Apologies, I have now clarified with an example at the end. Obviously the numeric operation I want to perform is more complicated than `*2`, it contains `if` statements etc. @joran, it does contain a variety of data types, and I can see that `apply()` converts each row to an atomic vector of type 'character'. Is there a way around this? At the moment I am having to perform `col = as.numeric(x['col'])` within the function on every variable – Harvs Sep 24 '19 at 15:34

0 Answers0