[R] [FORGED] Re: tibble question with a mean

Rolf Turner r@turner @end|ng |rom @uck|@nd@@c@nz
Fri Sep 21 03:38:26 CEST 2018


Please see inline below.

n 09/21/2018 01:07 PM, Peter Langfelder wrote:
> I don't know tibble, so I'll do the same with a plain data frame:
> 
> a =
> data.frame(x=LETTERS[1:4],y=1:4,z=rnorm(4),a=c("dog","cat","tree","ferret"))
>> a
>    x y           z      a
> 1 A 1 -0.08264865    dog
> 2 B 2  0.32344426    cat
> 3 C 3 -0.80416061   tree
> 4 D 4  1.27052529 ferret
>> mean(a[2:3])
> [1] NA
> Warning message:
> In mean.default(a[2:3]) : argument is not numeric or logical: returning NA
>> mean(as.matrix(a[2:3]))
> [1] 1.338395
> 
> The reason you get an error on mean(a[2:3]) is that a[2:3] is still a data
> frame (a special list) and you cannot simply apply mean to a list. You need
> to first convert to a matrix or vector which can then be fed to mean().

Perhaps

sapply(a[2:3],mean)?

cheers,

Rolf

> 
> Peter
> 
> 
> On Thu, Sep 20, 2018 at 5:50 PM Erin Hodgess <erinm.hodgess using gmail.com>
> wrote:
> 
>> Hello!
>>
>> Here is a toy tibble problem:
>>
>> xt <-
>> tibble(x=LETTERS[1:4],y=1:4,z=rnorm(4),a=c("dog","cat","tree","ferret"))
>> str(xt)
>> Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 4 obs. of  4 variables:
>>   $ x: chr  "A" "B" "C" "D"
>>   $ y: int  1 2 3 4
>>   $ z: num  0.3246 0.0504 0.339 0.4872
>>   $ a: chr  "dog" "cat" "tree" "ferret"
>> #No surprise
>>   xt %>% mean
>> [1] NA
>> Warning message:
>> In mean.default(.) : argument is not numeric or logical: returning NA
>> #surprised!
>> mean(xt[2:3])
>> [1] NA
>> Warning message:
>> In mean.default(xt[2:3]) : argument is not numeric or logical: returning NA
>>   xt[, 2:3] %>% mean
>> [1] NA
>> Warning message:
>> In mean.default(.) : argument is not numeric or logical: returning NA
>>
>> I have a feeling that I'm doing something silly wrong.  Has anyone run into
>> this, please?  I saw something like this on this list, but didn't see a
>> solution.
>>
>> Thanks,
>> Erin




More information about the R-help mailing list