Receiving an Error when Using the Uncount and Row_Number() functions

Hello,

I have a data frame where I would like to "uncount", or expand, the rows of my data set based on two columns: column 1 is the persons id number and column 2 is the length of time that they've received treatment. When I use:

df<-df%>%dplyr::group_by(id)%>%uncount(MD)%>%dplyr::mutate(Expnd=row_number())

Where id = persons id and MD= month difference, which is a numerical value like 10, 25, etc.

When I run the code I get this error: Error in rep(seq_nrow(data), w) : invalid 'times' argument

My first guess was that there were rows where MD is NA, which isn't the case. Any thoughts on how to remedy this?

Could you please turn this into a self-contained reprex (short for reproducible example)? It will help us help you if we can be sure we're all working with/looking at the same stuff.

install.packages("reprex")

If you've never heard of a reprex before, you might want to start by reading the tidyverse.org help page. The reprex dos and don'ts are also useful.

There's also a nice FAQ on how to do a minimal reprex for beginners, below:

What to do if you run into clipboard problems

If you run into problems with access to your clipboard, you can specify an outfile for the reprex, and then copy and paste the contents into the forum.

reprex::reprex(input = "fruits_stringdist.R", outfile = "fruits_stringdist.md")

For pointers specific to the community site, check out the reprex FAQ.

I agree with Mara, that your problem must be with your data, that we can't see.
because this works


df <- tribble (~id,~MD,
               123,1,
               234,2,
               456,4)

df<-df%>%dplyr::group_by(id)%>%uncount(MD)%>%dplyr::mutate(Expnd=row_number()) 
> df
# A tibble: 7 x 2
# Groups:   id [3]
     id Expnd
  <dbl> <int>
1   123     1
2   234     1
3   234     2
4   456     1
5   456     2
6   456     3
7   456     4
1 Like

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