### Rlabkey Authentication and Connection Setup Source: https://context7.com/labkey/labkey-api-r/llms.txt Demonstrates how to set default connection parameters for Rlabkey using API key or email/password authentication. It also shows how to verify the current user's identity. ```r library(Rlabkey) # API key authentication (recommended) labkey.setDefaults( baseUrl="https://www.labkey.org/", apiKey="abcdef0123456789abcdef0123456789" ) # Email/password authentication labkey.setDefaults( baseUrl="http://localhost:8080/labkey", email="user@example.com", password="mypassword" ) # Verify current user identity userInfo <- labkey.whoAmI(baseUrl="http://localhost:8080/labkey") print(userInfo$displayName) # Output: List with user details including displayName, email, userId, groups, CSRF token ``` -------------------------------- ### Authentication and Connection Setup Source: https://context7.com/labkey/labkey-api-r/llms.txt Set default connection parameters for Rlabkey and authenticate using API keys or email/password. Verify the current user's identity. ```APIDOC ## Authentication and Connection Setup ### Description Set default connection parameters for Rlabkey and authenticate using API keys or email/password. Verify the current user's identity. ### Method `library(Rlabkey)` `labkey.setDefaults()` `labkey.whoAmI()` ### Parameters #### Request Body (for `labkey.setDefaults`) - **baseUrl** (string) - Required - The base URL of the LabKey Server. - **apiKey** (string) - Optional - The API key for authentication. - **email** (string) - Optional - The user's email address for authentication. - **password** (string) - Optional - The user's password for authentication. #### Query Parameters (for `labkey.whoAmI`) - **baseUrl** (string) - Required - The base URL of the LabKey Server. ### Request Example ```r # API key authentication labkey.setDefaults( baseUrl="https://www.labkey.org/", apiKey="abcdef0123456789abcdef0123456789" ) # Email/password authentication labkey.setDefaults( baseUrl="http://localhost:8080/labkey", email="user@example.com", password="mypassword" ) # Verify current user identity userInfo <- labkey.whoAmI(baseUrl="http://localhost:8080/labkey") print(userInfo$displayName) ``` ### Response #### Success Response (200 for `labkey.whoAmI`) - **displayName** (string) - The display name of the current user. - **email** (string) - The email address of the current user. - **userId** (integer) - The unique identifier for the user. - **groups** (list) - A list of groups the user belongs to. - **CSRF token** (string) - The Cross-Site Request Forgery token for the session. #### Response Example (for `labkey.whoAmI`) ```json { "displayName": "Test User", "email": "user@example.com", "userId": 123, "groups": ["Users", "Administrators"], "CSRF token": "some_csrf_token" } ``` ``` -------------------------------- ### Rlabkey Data Querying with labkey.selectRows Source: https://context7.com/labkey/labkey-api-r/llms.txt Provides examples of querying data from LabKey Server using the `labkey.selectRows` function. Covers basic queries, column selection, filtering, sorting, and expanding lookup columns. ```r # Basic query - retrieve all rows and columns rows <- labkey.selectRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes" ) # Output: Data frame with stringsAsFactors=FALSE # Query with column selection rows <- labkey.selectRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes", colSelect=c("TextFld", "IntFld", "DateFld", "BooleanFld") ) # Query with filtering and sorting filter <- makeFilter( c("IntFld", "GREATER_THAN", "10"), c("TextFld", "CONTAINS", "test"), c("BooleanFld", "EQUAL", "TRUE") ) rows <- labkey.selectRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes", colFilter=filter, colSort="-IntFld", # Descending sort maxRows=100, rowOffset=0 ) # Query with lookup column expansion rows <- labkey.selectRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes", colSelect=c("TextFld", "IntFld", "Category", "Category/DisplayValue", "Category/Group/Name") ) ``` -------------------------------- ### LabKey R API Provenance Tracking Source: https://context7.com/labkey/labkey-api-r/llms.txt Enables the recording of provenance information for data processing pipelines. This involves creating provenance parameters and starting the recording process. Requires the `labkey` R package. ```r # Start provenance recording provenanceParams <- labkey.provenance.createProvenanceParams( name="Data Processing Pipeline", description="Processing raw data through QC and normalization", materialInputs=list("urn:lsid:labkey.com:Sample.123:RawSample_001"), materialOutputs=list("urn:lsid:labkey.com:Sample.123:Processed_001") ) recording <- labkey.provenance.startRecording( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", provenanceParams=provenanceParams ) recordingId <- recording$recordingId ``` -------------------------------- ### LabKey R API WebDAV Operations Source: https://context7.com/labkey/labkey-api-r/llms.txt Provides functions for interacting with LabKey WebDAV, including creating directories, checking path existence, deleting files/directories, and downloading folders. Assumes the `labkey` R package is installed and configured. ```r # Output: List with file information: id, href, text, contentLength, createdDate, lastModified, isCollection for(file in files) { print(paste(file$text, "-", file$contentLength, "bytes")) } ``` ```r # Create directory labkey.webdav.mkDir( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", remoteFilePath="new_analysis" ) ``` ```r # Create nested directories labkey.webdav.mkDirs( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", remoteFilePath="results/2023/Q1" ) ``` ```r # Check if path exists exists <- labkey.webdav.pathExists( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", remoteFilePath="data/archive" ) ``` ```r # Delete file or directory labkey.webdav.delete( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", remoteFilePath="temp/old_file.txt" ) ``` ```r # Download entire folder recursively labkey.webdav.downloadFolder( localBaseDir="/home/user/downloads", baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", remoteFilePath="complete_dataset", overwriteFiles=FALSE, mergeFolders=TRUE, showProgressBar=TRUE ) ``` -------------------------------- ### Interact with LabKey Pipeline Analysis Source: https://context7.com/labkey/labkey-api-r/llms.txt This section shows how to manage pipeline analysis jobs using the LabKey R API. It covers fetching available protocols, checking file analysis status, and starting new analysis jobs with specified parameters. ```r # Get available analysis protocols protocols <- labkey.pipeline.getProtocols( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", taskId="AssayImport", path="@pipeline", includeWorkbooks=FALSE ) print(protocols) # Check file analysis status status <- labkey.pipeline.getFileStatus( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", taskId="AssayImport", protocolName="ImportProtein", path="@pipeline", files=list("protein_data_001.tsv", "protein_data_002.tsv") ) # Start pipeline analysis analysisParams <- list( cutoff=0.05, foldChange=2.0, adjustmentMethod="BH" ) job <- labkey.pipeline.startAnalysis( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", taskId="DifferentialExpression", protocolName="StandardDE", path="@files/analysis", files=list("expression_matrix.csv"), jsonParameters=toJSON(analysisParams), pipelineDescription="Differential expression analysis from R" ) print(paste("Started job:", job$jobId)) ``` -------------------------------- ### Discover Schema and Metadata with LabKey R API Source: https://context7.com/labkey/labkey-api-r/llms.txt Retrieves information about schemas, queries, and query metadata from LabKey Server. Functions include listing schemas, listing queries within a schema, and getting detailed metadata for a specific query. Dependencies include the `Rlabkey` package. ```r # List all schemas in a folder schemas <- labkey.getSchemas( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples" ) print(schemas$schemaName) # Output: Data frame with schema names like "lists", "study", "core", "exp" # List queries in a schema queries <- labkey.getQueries( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists" ) print(queries$queryName) # Output: Data frame with query names and their field counts # Get detailed query metadata queryDetails <- labkey.getQueryDetails( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes" ) # Output: Data frame with columns: fieldName, caption, type, isNullable, isKeyField, # isAutoIncrement, isHidden, isSelectable, isUserEditable, lookup schema/query info ``` -------------------------------- ### User Impersonation for Testing LabKey Permissions Source: https://context7.com/labkey/labkey-api-r/llms.txt This code demonstrates how to use the LabKey R API to impersonate another user for testing permissions. It includes starting impersonation, performing actions as the impersonated user, and stopping impersonation. ```r # Impersonate user to test permissions labkey.security.impersonateUser( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", email="testuser@example.com" ) # Perform operations as impersonated user data <- labkey.selectRows( folderPath="/MyProject", schemaName="study", queryName="ProtectedData" ) # Stop impersonation labkey.security.stopImpersonating( baseUrl="http://localhost:8080/labkey" ) ``` -------------------------------- ### Rlabkey Advanced Filtering with makeFilter Source: https://context7.com/labkey/labkey-api-r/llms.txt Demonstrates the usage of the `makeFilter` function in Rlabkey for constructing complex filters for data queries. Examples include AND conditions, IN operators, string matching, missing value checks, date ranges, and experimental lineage filters. ```r # Multiple AND filters filter <- makeFilter( c("Age", "GREATER_THAN_OR_EQUAL", "18"), c("Status", "EQUALS", "Active"), c("DateEnrolled", "DATE_GREATER_THAN", "2023-01-01") ) # IN operator for multiple values filter <- makeFilter( c("RowId", "IN", "2;3;6;12") ) # String matching operators filter <- makeFilter( c("Name", "STARTS_WITH", "John"), c("Email", "CONTAINS", "@example.com"), c("Notes", "DOES_NOT_CONTAIN", "expired") ) # Missing value filters filter <- makeFilter( c("OptionalField", "MISSING", ""), c("RequiredField", "NOT_MISSING", "") ) # Date range filter filter <- makeFilter( c("CollectionDate", "DATE_BETWEEN", "2023-01-01,2023-12-31") ) # Experimental lineage filters filter <- makeFilter( c("LSID", "EXP_CHILD_OF", "urn:lsid:labkey.com:Sample.123:parent") ) rows <- labkey.selectRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="study", queryName="Demographics", colFilter=filter ) ``` -------------------------------- ### Create LabKey Domains with Custom Indices using R Source: https://context7.com/labkey/labkey-api-r/llms.txt Define and create LabKey domains with custom fields and indices. This involves manually specifying fields, creating index definitions, and then using these to create the domain. Functions require base URL, folder path, and domain design details. It also includes an example for deleting a domain. ```r # Define fields manually fields <- list( list(name="SubjectId", rangeURI="string", required=TRUE), list(name="VisitDate", rangeURI="dateTime", required=TRUE), list(name="Weight", rangeURI="double"), list(name="Height", rangeURI="double"), list(name="Notes", rangeURI="multiLine") ) # Create unique index indices <- labkey.domain.createIndices( colNames=list("SubjectId", "VisitDate"), asUnique=TRUE ) # Create domain with indices design <- labkey.domain.createDesign( name="ClinicalData", description="Clinical measurements", fields=fields, indices=indices ) result <- labkey.domain.create( baseUrl="http://localhost:8080/labkey", folderPath="/ClinicalStudy", domainKind="StudyDatasetVisit", domainDesign=design, options=list(dataset=list(datasetId=5001)) ) # Delete domain labkey.domain.drop( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", schemaName="lists", queryName="ObsoleteList" ) ``` -------------------------------- ### Get Query Views and Lookup Details with R Source: https://context7.com/labkey/labkey-api-r/llms.txt Retrieve views associated with a specific query in LabKey and fetch details about lookup fields. These functions require the base URL, folder path, schema name, and query name. ```r views <- labkey.getQueryViews( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes" ) lookupInfo <- labkey.getLookupDetails( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes", lookupKey="Category" ) ``` -------------------------------- ### LabKey R API Experiment and Assay Data Management Source: https://context7.com/labkey/labkey-api-r/llms.txt Demonstrates creating materials, data outputs, and experimental runs, then saving them as an assay batch. It also shows how to query lineage relationships. Requires the `labkey` R package. ```r # Create sample materials material1 <- labkey.experiment.createMaterial( config=list(name="Sample_001", properties=list(concentration=10.5)), sampleSetName="BloodSamples" ) material2 <- labkey.experiment.createMaterial( config=list(name="Sample_002", properties=list(concentration=8.3)), sampleSetName="BloodSamples" ) ``` ```r # Create data output dataOutput <- labkey.experiment.createData( config=list(name="Result_001", properties=list(instrument="MS-100")), dataClassName="MassSpecResults", dataFileUrl="file:///labkey/files/results/ms_run_001.raw" ) ``` ```r # Prepare assay results data frame resultsData <- data.frame( Sample=c("Sample_001", "Sample_002"), Protein=c("P1", "P1"), Intensity=c(1500.5, 1820.3), PValue=c(0.001, 0.002), stringsAsFactors=FALSE ) ``` ```r # Create experimental run run <- labkey.experiment.createRun( config=list( name="MS_Run_001", properties=list( runDate="2023-06-15", operator="John Doe", instrument="MassSpec-100" ) ), materialInputs=list(material1, material2), dataOutputs=list(dataOutput), dataRows=resultsData ) ``` ```r # Save assay batch with runs batchProps <- list( experimentDate="2023-06-15", labNotebook="NB-2023-42", technician="Jane Smith" ) batch <- labkey.experiment.saveBatch( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", protocolName="ProteinQuantification", batchPropertyList=list(name="Batch_2023_06", properties=batchProps), runList=list(run) ) print(paste("Saved batch with", length(batch$runs), "runs")) ``` ```r # Query lineage relationships lineage <- labkey.experiment.lineage( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", lsids=c("urn:lsid:labkey.com:Sample.123:Sample_001"), options=list( parents=TRUE, children=TRUE, depth=3, includeProperties=TRUE, includeRunSteps=TRUE ) ) # Output: Complex graph structure with nodes (seeds, parents, children) and edges ``` -------------------------------- ### Rlabkey Session-Based Interactive Data Exploration Source: https://context7.com/labkey/labkey-api-r/llms.txt Illustrates interactive data exploration using Rlabkey sessions. This includes creating a session, exploring schemas and queries, retrieving data, and navigating lookup relationships. ```r # Create interactive session object s <- getSession( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples" ) print(s) # Automatically displays available schemas # Explore schema and queries scobj <- getSchema(s, "lists") print(scobj) # Shows available queries in the schema # Access query object scobj$AllTypes # Returns query object with metadata # Retrieve data using session lkdata <- getRows(s, scobj$AllTypes) # Output: Data frame with all rows and columns from AllTypes query # Navigate lookup relationships lucols <- getLookups(s, scobj$AllTypes$Category) print(lucols) # Shows fields from the related Category lookup table # Chain lookups across multiple tables lucols2 <- getLookups(s, lucols[["Category/Group"]]) # Query with lookup columns included cols <- c(names(scobj$AllTypes)[2:6], names(lucols)[2:4]) simpledf <- getRows(s, scobj$AllTypes, colSelect=paste(cols, sep=",")) ``` -------------------------------- ### LabKey R API Assay Results using Session Object Source: https://context7.com/labkey/labkey-api-r/llms.txt Demonstrates how to establish a LabKey session, retrieve data from schemas, perform calculations, and save the results to an assay. This requires the `labkey` R package and appropriate permissions. ```r # Perform analysis and save results to assay s <- getSession( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples" ) ``` ```r # Get data for analysis scobj <- getSchema(s, "lists") simpledf <- getRows(s, scobj$AllTypes, colSelect=c("IntFld", "DoubleFld")) ``` ```r # Calculate summary statistics testtable <- simpledf[, c("IntFld", "DoubleFld")] results <- data.frame( Measure=c("colMeans", "colSums", "colSD"), IntFld=c( mean(testtable$IntFld, na.rm=TRUE), sum(testtable$IntFld, na.rm=TRUE), sd(testtable$IntFld, na.rm=TRUE) ), DoubleFld=c( mean(testtable$DoubleFld, na.rm=TRUE), sum(testtable$DoubleFld, na.rm=TRUE), sd(testtable$DoubleFld, na.rm=TRUE) ), stringsAsFactors=FALSE ) ``` ```r # Save results to assay bprops <- list( LabNotes="Statistical analysis from R", AnalysisDate=as.character(Sys.Date()) ) bpl <- list( name=paste("Batch", as.character(Sys.time())), properties=bprops ) assayInfo <- saveResults( session=s, assayName="SimpleMeans", resultDataFrame=results, batchPropertyList=bpl ) print(assayInfo) ``` -------------------------------- ### Record Provenance and Steps in LabKey Source: https://context7.com/labkey/labkey-api-r/llms.txt This snippet demonstrates how to record provenance information and add steps to a recording using the LabKey R API. It involves creating provenance parameters, adding recording steps, and completing the recording. ```r step1Params <- labkey.provenance.createProvenanceParams( recordingId=recordingId, name="Quality Control", description="Applied QC filters", properties=list( qcThreshold=0.95, passedSamples=145, failedSamples=3 ) ) labkey.provenance.addRecordingStep( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", provenanceParams=step1Params ) # ... perform actual processing ... step2Params <- labkey.provenance.createProvenanceParams( recordingId=recordingId, name="Normalization", description="Applied quantile normalization", properties=list(method="quantile", referenceDistribution="median") ) labkey.provenance.addRecordingStep( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", provenanceParams=step2Params ) # Complete recording completion <- labkey.provenance.stopRecording( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", provenanceParams=labkey.provenance.createProvenanceParams(recordingId=recordingId) ) ``` -------------------------------- ### Schema and Metadata Discovery Source: https://context7.com/labkey/labkey-api-r/llms.txt Discover available schemas, queries within schemas, and detailed metadata for specific queries. ```APIDOC ## API Endpoints for Schema and Metadata Discovery ### 1. List Schemas #### Description Retrieves a list of all schemas available within a specified LabKey folder. #### Method GET #### Endpoint `labkey.getSchemas(baseUrl, folderPath)` #### Parameters * **baseUrl** (string) - Required - The base URL of the LabKey server. * **folderPath** (string) - Required - The path to the LabKey folder. #### Response Example (Schemas) ```r schemas <- labkey.getSchemas( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples" ) print(schemas$schemaName) # Output: [1] "lists" "study" "core" "exp" ``` ### 2. List Queries in a Schema #### Description Retrieves a list of all queries (tables, views, etc.) within a specified schema. #### Method GET #### Endpoint `labkey.getQueries(baseUrl, folderPath, schemaName)` #### Parameters * **baseUrl** (string) - Required - The base URL of the LabKey server. * **folderPath** (string) - Required - The path to the LabKey folder. * **schemaName** (string) - Required - The name of the schema to list queries from. #### Response Example (Queries) ```r queries <- labkey.getQueries( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists" ) print(queries$queryName) # Output: [1] "AllTypes" "AllTypesCategories" "SomeOtherList" ``` ### 3. Get Query Details (Metadata) #### Description Retrieves detailed metadata for a specific query, including field names, data types, nullability, and lookup information. #### Method GET #### Endpoint `labkey.getQueryDetails(baseUrl, folderPath, schemaName, queryName)` #### Parameters * **baseUrl** (string) - Required - The base URL of the LabKey server. * **folderPath** (string) - Required - The path to the LabKey folder. * **schemaName** (string) - Required - The name of the schema containing the query. * **queryName** (string) - Required - The name of the query to get details for. #### Response Example (Query Details) ```r queryDetails <- labkey.getQueryDetails( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes" ) # Output: Data frame with columns: fieldName, caption, type, isNullable, isKeyField, isAutoIncrement, isHidden, isSelectable, isUserEditable, lookup schema/query info ``` ``` -------------------------------- ### Manage LabKey Domains (Schema) with R Source: https://context7.com/labkey/labkey-api-r/llms.txt Perform domain management operations including retrieving existing domain designs, inferring field definitions from a data frame, creating new domains, and creating domains with data loading. Requires base URL, folder path, and schema/query details. Some operations infer fields from data frames. ```r # Get existing domain design domain <- labkey.domain.get( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes" ) print(domain$fields) # Create new domain from data frame mydata <- data.frame( Name=c("Sample1", "Sample2"), Value=c(10.5, 20.3), Date=c("2023-01-01", "2023-01-02"), stringsAsFactors=FALSE ) # Infer field definitions from data fields <- labkey.domain.inferFields( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", df=mydata ) # Create domain design design <- labkey.domain.createDesign( name="MyList", description="A test list created from R", fields=fields ) # Create the domain result <- labkey.domain.create( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", domainKind="IntList", domainDesign=design ) # Create domain and load data in one operation labkey.domain.createAndLoad( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", name="MyNewList", description="Automatically created and loaded", df=mydata, domainKind="IntList" ) ``` -------------------------------- ### Manage LabKey Folders and Containers with R Source: https://context7.com/labkey/labkey-api-r/llms.txt Perform folder and container management tasks such as listing folders with permissions, creating new folders or workbooks, renaming containers, moving them to different parent paths, and deleting containers. Requires base URL and relevant folder paths. ```r # List folders with permissions folders <- labkey.getFolders( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", includeEffectivePermissions=TRUE, includeSubfolders=TRUE, depth=2 ) print(folders[, c("name", "path", "effectivePermissions")]) # Create new folder newFolder <- labkey.security.createContainer( baseUrl="http://localhost:8080/labkey", parentPath="/MyProject", name="Analysis_2023", title="2023 Data Analysis", description="Folder for 2023 analysis results", folderType="Collaboration" ) print(newFolder$path) # Create workbook workbook <- labkey.security.createContainer( baseUrl="http://localhost:8080/labkey", parentPath="/MyProject", name="SubjectAnalysis", title="Subject-specific Analysis", isWorkbook=TRUE ) # Rename container labkey.security.renameContainer( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject/OldName", name="NewName", title="New Title", addAlias=TRUE # Keep old name as alias ) # Move container labkey.security.moveContainer( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject/SubFolder", destinationParent="/AnotherProject", addAlias=FALSE ) # Delete container labkey.security.deleteContainer( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject/ObsoleteFolder" ) ``` -------------------------------- ### Querying Data with labkey.selectRows Source: https://context7.com/labkey/labkey-api-r/llms.txt Retrieve data from LabKey Server using `labkey.selectRows`. Supports basic queries, column selection, filtering, sorting, and expanding lookup columns. ```APIDOC ## Querying Data with labkey.selectRows ### Description Retrieve data from LabKey Server using `labkey.selectRows`. Supports basic queries, column selection, filtering, sorting, and expanding lookup columns. ### Method `labkey.selectRows()` ### Endpoint Not applicable (function-based R API) ### Parameters #### Request Body - **baseUrl** (string) - Required - The base URL of the LabKey Server. - **folderPath** (string) - Required - The path to the folder in LabKey Server. - **schemaName** (string) - Required - The name of the schema containing the query. - **queryName** (string) - Required - The name of the query or table. - **colSelect** (string array) - Optional - A list of columns to select. - **colFilter** (object) - Optional - A filter object created by `makeFilter()`. - **colSort** (string) - Optional - Column(s) to sort by (e.g., "-IntFld" for descending). - **maxRows** (integer) - Optional - Maximum number of rows to return. - **rowOffset** (integer) - Optional - Number of rows to skip from the beginning. ### Request Example ```r # Basic query - retrieve all rows and columns rows <- labkey.selectRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes" ) # Query with column selection rows <- labkey.selectRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes", colSelect=c("TextFld", "IntFld", "DateFld", "BooleanFld") ) # Query with filtering and sorting filter <- makeFilter( c("IntFld", "GREATER_THAN", "10"), c("TextFld", "CONTAINS", "test"), c("BooleanFld", "EQUAL", "TRUE") ) rows <- labkey.selectRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes", colFilter=filter, colSort="-IntFld", # Descending sort maxRows=100, rowOffset=0 ) # Query with lookup column expansion rows <- labkey.selectRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes", colSelect=c("TextFld", "IntFld", "Category", "Category/DisplayValue", "Category/Group/Name") ) ``` ### Response #### Success Response (200) - **Data Frame** - Contains the retrieved rows and columns from LabKey Server. #### Response Example ```r # Output of labkey.selectRows: # A data frame with selected rows and columns print(rows) ``` ``` -------------------------------- ### Session-Based Interactive Usage Source: https://context7.com/labkey/labkey-api-r/llms.txt Manage interactive sessions with LabKey Server, explore schemas and queries, retrieve data, and navigate lookup relationships. ```APIDOC ## Session-Based Interactive Usage ### Description Manage interactive sessions with LabKey Server, explore schemas and queries, retrieve data, and navigate lookup relationships. ### Method `getSession()` `getSchema()` `getRows()` `getLookups()` ### Endpoint Not applicable (function-based R API) ### Parameters #### Request Body (for `getSession`) - **baseUrl** (string) - Required - The base URL of the LabKey Server. - **folderPath** (string) - Required - The path to the folder in LabKey Server. #### Request Body (for `getSchema`) - **session** (object) - Required - The interactive session object returned by `getSession()`. - **schemaName** (string) - Required - The name of the schema to retrieve. #### Request Body (for `getRows`) - **session** (object) - Required - The interactive session object. - **queryObject** (object) - Required - The query object returned by accessing a schema. - **colSelect** (string array) - Optional - A list of columns to select. #### Request Body (for `getLookups`) - **session** (object) - Required - The interactive session object. - **columnObject** (object) - Required - A column object from a query. ### Request Example ```r # Create interactive session object s <- getSession( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples" ) # Explore schema and queries scobj <- getSchema(s, "lists") # Retrieve data using session lkdata <- getRows(s, scobj$AllTypes) # Navigate lookup relationships lucols <- getLookups(s, scobj$AllTypes$Category) # Query with lookup columns included cols <- c(names(scobj$AllTypes)[2:6], names(lucols)[2:4]) simpledf <- getRows(s, scobj$AllTypes, colSelect=paste(cols, sep=",")) ``` ### Response #### Success Response (200) - **Data Frame** - Contains the retrieved data from LabKey Server. - **Schema Object** - Metadata about the schema. - **Lookup Information** - Details about lookup columns. #### Response Example ```r # Output of getRows: Data frame with data print(lkdata) # Output of getSchema: Schema object print(scobj) # Output of getLookups: List with lookup details print(lucols) ``` ``` -------------------------------- ### Execute SQL Query Source: https://context7.com/labkey/labkey-api-r/llms.txt Execute custom SQL queries against LabKey schemas. Supports both static and parameterized queries. ```APIDOC ## POST /labkey.server.url/labkey/query/{{schemaName}}/executeSql ### Description Executes a custom SQL query against a specified schema in LabKey Server. This endpoint is useful for retrieving aggregated data, performing complex joins, and filtering results based on custom logic. ### Method POST ### Endpoint `labkey.executeSql(baseUrl, folderPath, schemaName, sql, maxRows, parameters)` ### Parameters * **baseUrl** (string) - Required - The base URL of the LabKey server. * **folderPath** (string) - Required - The path to the LabKey folder containing the schema. * **schemaName** (string) - Required - The name of the schema to query. * **sql** (string) - Required - The SQL query to execute. * **maxRows** (integer) - Optional - The maximum number of rows to return. * **parameters** (list) - Optional - A list of parameters to use for a parameterized query. ### Request Example (Parameterized Query) ```r sql <- "SELECT * FROM Samples WHERE CreatedDate > ? AND Status = ?" results <- labkey.executeSql( baseUrl="http://localhost:8080/labkey", folderPath="/myproject", schemaName="samples", sql=sql, parameters=list("2023-01-01", "Active") ) ``` ### Response #### Success Response (200) - **results** (data.frame) - A data frame containing the results of the SQL query. #### Response Example ```r # For a query returning aggregated data # Category SumOfIntFld AvgOfDoubleFld RecordCount # # 1 Category A 150 25.5 10 # 2 Category B 100 15.2 8 ``` ``` -------------------------------- ### Execute SQL Query with LabKey R API Source: https://context7.com/labkey/labkey-api-r/llms.txt Executes custom or parameterized SQL queries against LabKey Server. Supports `SELECT` statements and returns results as an R data frame. Dependencies include the `Rlabkey` package. ```r # Execute custom SQL query sql <- "SELECT AllTypesCategories.Category AS Category, SUM(AllTypes.IntFld) AS SumOfIntFld, AVG(AllTypes.DoubleFld) AS AvgOfDoubleFld, COUNT(*) AS RecordCount FROM AllTypes LEFT JOIN AllTypesCategories ON (AllTypes.Category = AllTypesCategories.TextKey) WHERE AllTypes.Category IS NOT NULL GROUP BY AllTypesCategories.Category ORDER BY SumOfIntFld DESC" results <- labkey.executeSql( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", sql=sql, maxRows=100 ) # Output: Data frame with aggregated results # Parameterized SQL query sql <- "SELECT * FROM Samples WHERE CreatedDate > ? AND Status = ?" results <- labkey.executeSql( baseUrl="http://localhost:8080/labkey", folderPath="/myproject", schemaName="samples", sql=sql, parameters=list("2023-01-01", "Active") ) ``` -------------------------------- ### Perform WebDAV File Operations with R Source: https://context7.com/labkey/labkey-api-r/llms.txt Interact with files on the LabKey Server using WebDAV protocol. This includes uploading local files, downloading files from the server, and listing the contents of remote directories. Requires base URL, folder path, and file paths. ```r # Upload file to server success <- labkey.webdav.put( localFile="/home/user/analysis/results.csv", baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", remoteFilePath="data/analysis_results.csv", description="Analysis results from R script" ) # Download file from server success <- labkey.webdav.get( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", remoteFilePath="data/input_data.csv", localFilePath="/tmp/downloaded_data.csv", overwrite=TRUE, showProgressBar=TRUE ) # List directory contents files <- labkey.webdav.listDir( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", remoteFilePath="data/" ) ``` -------------------------------- ### Insert Data with LabKey R API Source: https://context7.com/labkey/labkey-api-r/llms.txt Inserts single or multiple rows into LabKey Server lists or tables. Requires data frames with columns matching the target schema. Supports optional audit options. Dependencies include the `Rlabkey` package. ```r # Insert single row newrow <- data.frame( DisplayFld="Inserted from R", TextFld="how its done", IntFld=98, DoubleFld=12.345, DateTimeFld="03/01/2010", BooleanFld=FALSE, LongTextFld="Four score and seven years ago", RequiredText="Veni, vidi, vici", RequiredInt=0, Category="LOOKUP2", stringsAsFactors=FALSE ) insertedRow <- labkey.insertRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="lists", queryName="AllTypes", toInsert=newrow ) newRowId <- insertedRow$rows[[1]]$RowId print(paste("Inserted RowId:", newRowId)) # Output: List with command, rowsAffected, rows (array of inserted records), schemaName, queryName # Insert multiple rows newrows <- data.frame( SubjectId=c("S001", "S002", "S003"), Age=c(25, 30, 42), Gender=c("M", "F", "M"), Status=c("Active", "Active", "Inactive"), stringsAsFactors=FALSE ) result <- labkey.insertRows( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", schemaName="study", queryName="Demographics", toInsert=newrows, options=list( auditBehavior="DETAILED", auditUserComment="Batch import from R analysis script" ) ) print(paste("Inserted", result$rowsAffected, "rows")) ``` -------------------------------- ### Configure LabKey API Client Settings Source: https://context7.com/labkey/labkey-api-r/llms.txt This snippet covers advanced configuration options for the LabKey R API client. It includes accepting self-signed certificates, setting custom cURL options, enabling debug mode, configuring WAF encoding, and getting/setting module properties. ```r # Accept self-signed SSL certificates (development only) labkey.acceptSelfSignedCerts() # Set custom cURL options labkey.setCurlOptions( ssl_verifyhost=FALSE, ssl_verifypeer=FALSE, timeout=300, verbose=TRUE ) # Enable debug mode for troubleshooting labkey.setDebugMode(TRUE) # Configure WAF encoding for SQL/script content labkey.setWafEncoding(TRUE) # Get module property propValue <- labkey.getModuleProperty( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", moduleName="MyModule", propName="defaultThreshold" ) # Set module property labkey.setModuleProperty( baseUrl="http://localhost:8080/labkey", folderPath="/MyProject", moduleName="MyModule", propName="defaultThreshold", value="0.95" ) ``` -------------------------------- ### Advanced Filtering with makeFilter Source: https://context7.com/labkey/labkey-api-r/llms.txt Construct complex filter criteria for data queries using the `makeFilter` function. Supports various operators including IN, string matching, missing values, date ranges, and experimental lineage. ```APIDOC ## Advanced Filtering with makeFilter ### Description Construct complex filter criteria for data queries using the `makeFilter` function. Supports various operators including IN, string matching, missing values, date ranges, and experimental lineage. ### Method `makeFilter()` ### Endpoint Not applicable (function-based R API) ### Parameters #### Request Body (for `makeFilter`) - **...** (multiple arguments) - Each argument is a vector representing a filter condition: - **Column Name** (string) - The name of the column to filter. - **Operator** (string) - The comparison operator (e.g., "GREATER_THAN", "EQUALS", "IN", "STARTS_WITH", "MISSING"). - **Value** (string or array) - The value(s) to compare against. ### Request Example ```r # Multiple AND filters filter <- makeFilter( c("Age", "GREATER_THAN_OR_EQUAL", "18"), c("Status", "EQUALS", "Active"), c("DateEnrolled", "DATE_GREATER_THAN", "2023-01-01") ) # IN operator for multiple values filter <- makeFilter( c("RowId", "IN", "2;3;6;12") ) # String matching operators filter <- makeFilter( c("Name", "STARTS_WITH", "John"), c("Email", "CONTAINS", "@example.com"), c("Notes", "DOES_NOT_CONTAIN", "expired") ) # Missing value filters filter <- makeFilter( c("OptionalField", "MISSING", ""), c("RequiredField", "NOT_MISSING", "") ) # Date range filter filter <- makeFilter( c("CollectionDate", "DATE_BETWEEN", "2023-01-01,2023-12-31") ) # Experimental lineage filters filter <- makeFilter( c("LSID", "EXP_CHILD_OF", "urn:lsid:labkey.com:Sample.123:parent") ) # Using the filter with labkey.selectRows rows <- labkey.selectRows( baseUrl="http://localhost:8080/labkey", folderPath="/apisamples", schemaName="study", queryName="Demographics", colFilter=filter ) ``` ### Response #### Success Response (200) - **Data Frame** - Contains the rows that match the specified filter criteria. #### Response Example ```r # Output of labkey.selectRows with filter: # A data frame with filtered data print(rows) ``` ```