apply() is giving NA values for every column

前端 未结 3 1149
悲哀的现实
悲哀的现实 2021-01-03 04:37

I\'ve been having this strange problem with apply lately. Consider the following example:

set.seed(42)
df <- data.frame(cars, foo = sample(LE         


        
3条回答
  •  遥遥无期
    2021-01-03 05:06

    The first sentence of the description for ?apply says:

    If X is not an array but an object of a class with a non-null dim value (such as a data frame), apply attempts to coerce it to an array via as.matrix if it is two-dimensional (e.g., a data frame) or via as.array.

    Matrices can only be of a single type in R. When the data frame is coerced to a matrix, everything ends up as a character if there is even a single character column.

    I guess I owe you an description of an alternative, so here you go. data frames are really just lists, so if you want to apply a function to each column, use lapply or sapply instead.

提交回复
热议问题