# Using R in Knime

Hi,

I have written a function in R. It runs perfectly in R but does not returns same output when I run it in KNIME. Below is the function:

mapping<- function(x)
{
output<<- c()
flag<<-c()
p<- rownames(x)
for (i in 1: nrow(x))
{
y<- x[p[1],]
y<- c(as.vector(y))
y<- unlist(y)

for (j in 1:1000)
{
k<- c(as.vector(x[y[j],]))
k<- unlist(k)
y<- c(y,k)
y<- unique(y)
if(length(y)-j <= -3) {break}
}
q = which(p%in%y)
x<- x[-q,]
p<- p[-which(p%in%y)]
y<- y[-which(y%in%"0")]
y<- y[-which(is.na(y)==T)]
n<-rep(i, length(y))
output<<-c(output,y)
flag<<-c(flag,n)
if(nrow(x) == 0) {break}
}
mapped<<- data.frame(output,flag)
return(mapped)
return(flag)
}

mapping(x)

The dataset being used is:

a  b c
1  1  2 0
2  1  2 3
3  2  3 7
5  5  6 0
6  5  6 8
7  3  7 0
8  6  8 0
9  9 10 0
10 9 10 0

Please note that all the variales are 'character' and not 'Integer'. I have used follwong code in R to generate this dataset:

x<- data.frame(c(1,1,2,5,5,3,6,9,9),
c(2,2,3,6,6,7,8,10,10),
c(0,3,7,0,8,0,0,0,0))

colnames(x)<- c("a","b","c")
rownames(x)<- c(1,2,3,5,6,7,8,9,10)
x\$a<- as.character(x\$a)
x\$b<- as.character(x\$b)
x\$c<- as.character(x\$c)

And in Knime I import this dataframe form Excel as character then using "RowId' node I assign row name and then read this in 'R Snippet (x - Knime.in)' node, where I write the above fucntion.

Also, R output looks like:

output flag
1      1    1
2      2    1
3      3    1
4      7    1
5      5    2
6      6    2
7      8    2
8      9    3
9     10    3

While in Knime it generates empty dataset.

Thnaks,

Saurav

Hi Saurav,

the KNIME R Integration passes Strings as factors to R. This means you will need to add the following line to the top of your code:

knime.in[] <- lapply(knime.in, as.character)

I hope that helps!

Greetings, Jonathan

1 Like