apply() is giving NA values for every column

前端 未结 3 1152
悲哀的现实
悲哀的现实 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 04:57

    apply works on a matrix, and a matrix must be of all one type. So df is being transformed into a matrix, and since it contains a character, all the columns are becoming character.

    > apply(df, 2, class)
          speed        dist         foo 
    "character" "character" "character" 
    

    To get what you want, check out the colwise and numcolwise functions in plyr.

    > numcolwise(mean)(df)
      speed  dist
    1  15.4 42.98
    

提交回复
热议问题