Input and out file location in R

Hello, I have the following R script that asks for the file location (input) and save the processed data (output) in the same folder. I am not sure as how to run in KNIME and how to modify the script to allow excles sheet as input and choose the output location and format in KNIME .

Load necessary libraries

library(readxl) # For reading Excel files
library(pracma) # For numerical operations
library(writexl) # For writing Excel files

Define the ALS smoothing function with proper matrix dimensions

als ← function(y, lambda, p, niter=10) {
L ← length(y)
D ← diff(diag(L), diff = 2) # Create second derivative matrix
D ← D[-1,] # Adjust the dimensions of D to fit the operation

w ← rep(1, L)

for (i in 1:niter) {
W ← diag(w, L, L)
Z ← solve(t(D) %% W %% D + lambda * diag(L - 2), t(D) %% W %% y)
w ← p * (y > Z) + (1-p) * (y <= Z)
Z ← c(y[1], Z, y[L]) # Optionally extend Z to match y’s length if needed
}
return(Z)
}

Use file.choose() to allow the user to select the Excel file interactively

cat(“Please select the Excel file through the file dialog.\n”)
file_path ← file.choose()

Check if a file was selected and if it exists

if (file_path == “”) {
cat(“No file was selected.\n”)
} else if (!file.exists(file_path)) {
cat(“Error: File does not exist at the specified path:”, file_path, “\n”)
} else {

Read the data from the Excel file

data ← read_excel(file_path)

Applying ALS smoothing to all variable columns except the first one (Concentration)

results ← data # Copy the original data to store results
for (i in 2:ncol(data)) {
results[,i] ← als(data[,i], lambda=1e6, p=0.01) # adjust lambda and p as necessary
}

Save the filtered data to a new Excel file

new_file_path ← gsub(“\.xlsx”, “_AsLS.xlsx”, file_path) # Change the file name
write_xlsx(results, new_file_path)

Confirm the file has been saved

cat(“Filtered data saved as:”, new_file_path, “\n”)
}

@Pejman_Hm welcome to the KNIME forum. You could provide the path of the Excel file as flow variable like in this example

https://docs.knime.com/latest/analytics_platform_file_handling_guide/index.html#introduction

1 Like

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