0

I have a dataframe with rows such as:

dt <- data.frame(id = c(1,1), start = as.Date(c("2020-01-01", "2021-02-01")), end = as.Date(c("2020-12-31", "2022-01-31")), cancelled = as.Date(c("2021-01-10", NA)))

dt
## id      start        end  cancelled
##  1 2020-01-01 2020-12-31 2021-01-10
##  1 2021-02-01 2022-01-31       <NA>

and I would like to pivot_longer to obtain:

id   date        action
1    2020-01-01  start
1    2020-12-31  end
1    2021-01-10  cancelled
1    2021-02-01  start
1    2022-01-31  end

I thought that this would work, but it produces an error:

dt %>% 
pivot_wider(
  cols = !id, 
  names_to = "date", 
  values_to = "action")

Error: 2 components of `...` were not used.

We detected these problematic arguments:
* `names_to`
* `values_to`

Did you misspecify an argument?
3
  • use argument cols as -id instead of !id Commented Mar 30, 2021 at 8:52
  • 1
    You are using pivot_wider instead of pivot_longer. Use pivot_longer(dt, cols = !id, names_to = "date", values_to = "action", values_drop_na = TRUE) Commented Mar 30, 2021 at 8:53
  • @RonakShah DOH !!! Thank you ! Commented Mar 30, 2021 at 8:54

1 Answer 1

1
dt %>% pivot_longer(-id) %>% filter(!is.na(value))

# A tibble: 5 x 3
     id name      value     
  <dbl> <chr>     <date>    
1     1 start     2020-01-01
2     1 end       2020-12-31
3     1 cancelled 2021-01-10
4     1 start     2021-02-01
5     1 end       2022-01-31
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.