I have a sparklyr dataframe similar to the one generated with the code below.
# Load libraries
library(sparklyr)
library(dplyr)
library(magrittr)
# Connect to spark
sc <- spark_connect(master = "local")
# Creating example data
df <- read.table(text = "firm sector chapter
A x 11
B x 12
C y 21
D x 11
E z 31
F y 22
G z 32", header=TRUE)
# Copying data to spark instance
sdf <- copy_to(sc,df, name = "sdf", overwrite=TRUE)
I want to create a group_id by sector such that:
- firms in sector
yeach belong to their own group, and - firms in other sectors are grouped into a single id,
resulting in the following table
# Source: spark<sdf2> [?? x 4]
firm sector chapter group
<chr> <chr> <int> <int>
1 A x 11 1
2 B x 12 1
3 C y 21 2
4 D x 11 1
5 E z 31 4
6 F y 22 3
7 G z 32 4
But so far, I'm struggling even with creating a group_id at the sector level. I have tried:
sdf %>% mutate(group_id = group_indices(sector))sdf %>% group_by(sector) %>% mutate(group_id = cur_group_id())sdf %>% group_by(sector) %>% mutate(group_id = seq_along(sector))
But I get error messages. How can I achieve this in SparklyR?