如何在Tableau中调用无返回值R函数并读取其生成的数据框
Got it, let's work through this. You're right—when using Rserve with Tableau, you're limited to returning those four primitive types, so exporting the DataFrame to a CSV and then reading it back into Tableau is a solid workaround. Here's how to implement it:
Step 1: Create a Tableau Calculation Field to Trigger R's CSV Export
You'll use one of Tableau's SCRIPT_* functions to call your R code. Since we just need to trigger the file write (and Tableau requires a return value), SCRIPT_INT works perfectly here (we'll return a dummy integer to satisfy the type requirement).
Here's the full code for your Tableau calculated field:
SCRIPT_INT(" # Define your R function write_csv <- function(perc) { # Build the initial DataFrame employee <- c('John Doe','Peter Gynn','Jolie Hope') salary <- c(21000, 23400, 26800) data <- data.frame(employee, salary) # Calculate the SpendAmt field data$SpendAmt <- data$salary * (perc / 100) # Export to CSV—update the file path to your desired location! # For Windows, use double backslashes (e.g., 'C:\\Temp\\Sample_Test.csv') or forward slashes write.csv(data, 'C:/Your/Full/File/Path/Sample_Test.csv', row.names = FALSE) # Return a dummy integer to meet Tableau's return type requirement return(1) } # Call the function with your percentage value/field # Replace .arg1's input with your Tableau field or a fixed number (e.g., 10 for 10%) write_csv(.arg1) ", [Your Percentage Field])
Key Notes:
- File Path: Update the path in
write.csvto a location both Rserve and Tableau can access. Use absolute paths to avoid confusion—relative paths might not work across different environments. - Parameter Input: Replace
[Your Percentage Field]with either a fixed value (like15for 15%) or a field from your Tableau dataset that holds the percentage you want to use. - Return Value: The
return(1)is non-negotiable here—Tableau expects a value matching theSCRIPT_*type you're using, so this dummy integer keeps the connection working even though we don't care about the actual return data.
Step 2: Read the CSV Back into Tableau
Once you run the calculation field (add it to a view, for example), the CSV will be generated. Then:
- Go to Data > New Data Source
- Select Text File and navigate to the
Sample_Test.csvyou just created - Connect to it, and you'll have full access to the DataFrame with the
SpendAmtcalculation included.
内容的提问来源于stack exchange,提问作者Varun kadekar

