Home > Blockchain >  Creating function that inputs a vector and numeric
Creating function that inputs a vector and numeric

Time:06-17

My function does not work. Here's the data frame (it is bigger than this, but the rest is irrelevant to this function):

df <- data.frame(TypesOfTouch = c("Hug","Handshake","Kiss"))

And the vector I will use to check if it matches with the data frame and convert to their respective numerics:

Vec <- c("Stroke","Caress","Hug")

So I wrote this function:

Converter <- function(VectorInp,Col){
 for (i in 1:nrow(df)){
  if (is.element(df[i,Col],VectorInp)){
   df[i,Col] <- which(VectorInp == df[i,Col])
  }
 }

Converter(Vec,1)

The weird thing is that the code works when it is not applied to a function as shown above. Therefore, I was wondering if the problem could be that it couldn't input a vector. However, it was still a vector as input (checked using (~is.vector(VectorInp)).

For reference, this code works and does the same (but it is not a function):

for (i in 1:nrow(df)){
 if (is.element(df[i,1],Vec)){
  df[i,1] <- which(Vec == df[i,1])
 }
}

Any ideas?

CodePudding user response:

You're close. The reason you have no output is, that your function doesn't return something. Currently you didn't include a command that allows the modified data frame to leave the function scope.

So you may want to do:

Converter <- function(VectorInp, Col) {
  for (i in 1:nrow(df)) {
    if (is.element(df[i, Col], VectorInp)) {
      df[i, Col] <- which(VectorInp == df[i, Col])
    }
  }
  return(df)
}

  
Converter(Vec, 1)
#        Type
# 1         3
# 2 Handshake
# 3      Kiss

Instead of return(df) you may also briefly write just df.


Data:

df <- data.frame(Type = c("Hug", "Handshake", "Kiss"))
Vec <- c("Stroke", "Caress", "Hug")
  • Related