Skip to content
Prev 392414 / 398503 Next

Odd behavior of a function within apply

Dear Erin,

The problem is that the data frame gets coerced to a character matrix, 
and the only column with "" entries is the 9th (the second one you 
supplied):

as.matrix(test1.df)
    X1_1_HZP1 X1_1_HBM1_mon X1_1_HBM1_yr
1  "48160"   "December"    "2014"
2  "48198"   "June"        "2018"
3  "80027"   "August"      "2016"
4  "48161"   ""            NA
5  NA        ""            NA
6  "48911"   "August"      "1985"
7  NA        "April"       "2019"
8  "48197"   "February"    "1993"
9  "48021"   ""            NA
10 "11355"   "December"    "1990"

(Here, test1.df only contains the three columns you provided.)

A solution is to use sapply:

 > sapply(test1.df, count1a)
     X1_1_HZP1 X1_1_HBM1_mon  X1_1_HBM1_yr
             2             3             3


I hope this helps,
  John
On 2022-08-08 1:22 p.m., Erin Hodgess wrote:
Message-ID: <565e3f72-a449-753f-ebee-b44d0f62eb2b@mcmaster.ca>
In-Reply-To: <9435_1659979524_278HPNvu030617_CACxE24m2C3vzwGpYYoWVrLpLcx7jAK1FnnRHorwm-YFwDDzqPg@mail.gmail.com>