Skip to content
Advertisement

How to add a vector to a table in backend using dbplyr (R)

I created a table from a data source using tbl(). I need to add a column including 1:nrow() to my dataset and tried different methods but I didn’t succeed. My code is as below:

nrow_df1 <- df1 %>% summarise(n = n()) %>% pull(n)

df1 <- df1 %>% mutate(ID = 1:nrow_df1, step = 1)

It doesn’t add column ID to my dataset and only adds column step.

Using as.data.frame(), it works but so slow.

Do you have any ideas? thanks in advance

Advertisement

Answer

I found the answer. It is to use row_number() but as.numeric is also needed to convert the output from integer64 to numeric:

df1 <- df1 %>% mutate(ID = as.numeric(row_number(a column)), step = 1)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement