Compile information on the same line

Asked

Viewed 18 times

1

I need help to compile information on a single line. Here’s an example of df:

library(tidyverse)
df <- tibble(
  Name = c("A", "A", "B", "B"),
  Week = c(100, NA, 200, NA),
  Weekend = c(NA, 2000, NA, 1500)
  )

The result I need would be in this format:

inserir a descrição da imagem aqui

1 answer

1


It is possible to obtain the desired result with the code below, which groups the results by Name calculates the maximum value of columns Week and Weekend:

df %>%
  group_by(Name) %>%
  summarise(Week = max(Week, na.rm = TRUE), 
            Weekend = max(Weekend, na.rm = TRUE))
# A tibble: 2 x 3
  Name   Week Weekend
  <chr> <dbl>   <dbl>
1 A       100    2000
2 B       200    1500

The same result would be obtained with virtually any other statistic like min, median, mean etc..

Problems may arise if the data has another format, such as more than one observation NA by group and column.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.