Error in mean(.x) : object '.x' not found while combing rowise with select

I am trying to combine select with a rowise operation and I get this error :

fruits <- tribble(
  ~"fruit", ~"height_1", ~"height_2", ~"height_3", ~"width", ~"weight",
  "Banana", 4, 4.2, 3.5, 1, 0.5,
  "Strawberry", 1, .9, 1.2, 1, .25,
  "Pineapple", 18, 17.7, 19.2, 6, 3
)

fruits |> 
  rowwise(fruit) |>
  select(contains("height"))
  mutate(height_mean = mean(.x))

Adding missing grouping variables: `fruit`
Error in `mutate()`:
! Problem while computing `height_mean = list(mean(.x))`.
ℹ The error occurred in row 1.
Caused by error in `mean()`:
! object '.x' not found

How do I fix this?

I am a complete noob at 4 (today is day 6 of learning r :smile: ).

Created on 2022-09-17 with reprex v2.0.2

Hey, do you want to calculate the height for each fruit and create a new column?

I am being pragmatist and this is what I think will solve your problem

library(tidyverse)
library(dplyr)

fruits <- as.tibble(
  ~"fruit", ~"height_1", ~"height_2", ~"height_3", ~"width", ~"weight",
  "Banana", 4, 4.2, 3.5, 1, 0.5,
  "Strawberry", 1, .9, 1.2, 1, .25,
  "Pineapple", 18, 17.7, 19.2, 6, 3
)

fruits<- as.data.frame(fruits)

df <- fruits %>% 
  select(contains("height")) 

fruits$height_mean <- df %>% rowMeans()
1 Like

You cant use .x syntax without putting a tilde ~ in front of it

Is this what you are trying to do?

library(dplyr)

fruits <- tribble(
    ~"fruit", ~"height_1", ~"height_2", ~"height_3", ~"width", ~"weight",
    "Banana", 4, 4.2, 3.5, 1, 0.5,
    "Strawberry", 1, .9, 1.2, 1, .25,
    "Pineapple", 18, 17.7, 19.2, 6, 3
)

fruits |> 
    rowwise(fruit) |>
    select(contains("height")) |>
    mutate(height_mean = mean(c_across()))
#> Adding missing grouping variables: `fruit`
#> # A tibble: 3 × 5
#> # Rowwise:  fruit
#>   fruit      height_1 height_2 height_3 height_mean
#>   <chr>         <dbl>    <dbl>    <dbl>       <dbl>
#> 1 Banana            4      4.2      3.5        3.9 
#> 2 Strawberry        1      0.9      1.2        1.03
#> 3 Pineapple        18     17.7     19.2       18.3

Created on 2022-09-17 with reprex v2.0.2

3 Likes

Yes! Thank you Andre :innocent:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.