weird mutate situation

name cats happiness_level 
Leo   5      10                           

I have data like the above.. and essentially I want to uncount, but only ensure one row has happiness level of 10. the others should have happiness level 0 or NA. is there an easy way to do this? I am doing this to create a weighted average, where one cat is weighted 10 happiness level, but the other 4 cats have 0 happiness level

so this is what I want as the output somehow..

name cats happiness_level 
Leo   1      10       
Leo   1      0
Leo   1      0
Leo   1      0
Leo   1      0
          

Here is one way to get to your desired outcome.

library(tidyverse)

df = data.frame(name = 'Leo',
                cats = 5,
                happiness_level = 10)

out = uncount(df, cats, .remove = F) %>%
  group_by(name) %>%
  mutate(happiness_level = ifelse(row_number() > 1, 0, happiness_level)) %>%
  ungroup()
  
out
#> # A tibble: 5 Ă— 3
#>   name   cats happiness_level
#>   <chr> <dbl>           <dbl>
#> 1 Leo       5              10
#> 2 Leo       5               0
#> 3 Leo       5               0
#> 4 Leo       5               0
#> 5 Leo       5               0

Created on 2022-12-19 with reprex v2.0.2.9000

2 Likes

thank u soo much Scotty! what does .Remove = F mean

It checks to see if you want to remove the “uncount” column. If set to TRUE in this case, cats would be removed.

1 Like

thank u!! is there a way to uncount where the uncount variable goes to "1" for each row

My apologies on keeping those as 5. I don’t know how to do that within uncount(), but you could add the following at the end after ungroup().

%>%
mutate(cats = 1)
1 Like

This topic was automatically closed 42 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.