Why is R code that works in R not working in Alteryx R??
I am copying my code from R that I've written using for loop to R in Alteryx and it's giving me an error.
I am not using any packages, but I am using for loop to make calculations to replace rows with Nulls using data in data frame. The code works fine in R and I get all the calculations I need, and when I copy the code over to R in Alteryx, it's giving me an error.
Sample code:
for (i in 2:nrow(test)) {
test$new[i] = (test$new[i-1] * (1 + test$growth[i-1]))
}
Error message:
Error in test$new[i] = (test$new[i-1] * (1 + test$growth[i-1]))
replacement has length zero
If I can't just copy over the code from R, what's the benefit of having R in Alteryx?
Solved! Go to Solution.
So I have data imported as an input from database structured like
date | new | growth |
2021/02/01 | 1000 | 0.01 |
2021/02/02 | NA | 0.01 |
2021/02/03 | NA | 0.02 |
2021/02/04 | NA | 0.02 |
This is just sample data, but I have a dates column, new column that has value for only the first row, and growth column that can have different growth for different dates.
I am querying this data frame from my database and calling it a test in Alteryx.
The goal I'm trying to achieve using R in Alteryx is filling out NAs in new column with calculation shown in my previous post.
Hi @seungp
Here's a workflow that works using the R tool
Here's the code in that's in the R tool
test = read.Alteryx("#1", mode="data.frame") #Read data from Alteryx
for (i in 2:nrow(test)) {
test$new[i] = (test$new[i-1] * (1 + test$growth[i-1]))
}
write.Alteryx(test, 1) #Write results back to alteryx
As you can see once you add in the function calls to read in the data as a dataframe and write the results back out, the code works correctly.
One thing to note is that the read.Alteryx() returns a typed dataframe, so the [new] column is a string and your code as written can't perform the math operations on string fields. I deleted the NA in the input data and forced the datatype to double.
The Multi-Row tool is there just to show how to perform the same operation in native Alteryx. There's a small overhead to invoking the R runtime . If your data set is small, the overall workflow will run faster if you can perform the task using native Alteryx tools
Dan