How to extend my code that works by group to all data and combine the results in a unique table

Dear all,
I'm trying to analyse the effect of "Factor1" and "Factor2" on the response variable "perf" by "location", and obtaining at the end my original dataset associated to the lsmeans and tukey groups letters. Here below the code I'm using that gives me exactly what I need but only by location, my need is : how can I extend it in a way my output combines results of all locations, i.e, output of lsmeans and CLD by location :slight_smile:

library(multcomp)
library(lsmeans)
library(dplyr)
library(broom)

output <- as.data.frame(dataset)
output$perf <- as.numeric(output$perf)
output$factor1 <- as.factor(output$factor1)
output$factor2 <- as.factor(output$factor2)
output <- output %>% 
           group_by(location) %>% 
           mutate(row=row_number()) 

model <- lm(perf ~ factor1 + factor2, data = output)
lsmeans <- lsmeans(model, ~ factor1)
CLD = cld(lsmeans,
            alpha   = 0.05,
            Letters = letters,
            adjust  = "tukey")         

output <- left_join(output, CLD, by = "factor1")

Thank you in advance for your help !

best guess (lack of example data provided)

library(multcomp)
library(lsmeans)
library(dplyr)
library(broom)
 

# assuming your data is called `output` ....

lsplit <- split(output,~location)

all_results <- lapply(lsplit,\(x){
  
  model <- lm(perf ~ factor1 + factor2, data = x)
  lsmeans <- lsmeans(model, ~ factor1)
  CLD = cld(lsmeans,
            alpha   = 0.05,
            Letters = letters,
            adjust  = "tukey")         
  
  x <- left_join(x, CLD, by = "factor1")
  x
})

all_results

Dear @nirgrahamuk ,
Many thanks for your help !
I think lapply is what I need but applying yur suggestion , I didn't get the output I need .
To give you a view about my data, here is a sample of the entry data "output" :

group perf factor1 Factor2
1 32 1 1
1 44 1 2
1 58 1 3
1 76 2 1
1 73 2 2
1 37 2 3
1 52 3 1
1 78 3 2
1 60 3 3
2 93 1 1
2 78 1 2
2 25 1 3
2 97 2 1
2 85 2 2
2 60 2 3
2 70 3 1
2 62 3 2
2 95 3 3

The output I'm looking to obtain is the original dataset + the "lsmeans" and "groups" columns.
Many thanks again !

If your issue is that you want to recombine the split out table with added stats to a single table, then you can use dplyr::bind_rows on the previous result to collate that.