-1

I'm working on a Kaggle Kernel relating to FIFA 19 data(https://www.kaggle.com/karangadiya/fifa19) and trying to create a function which adds up numbers in a column. The column has values like 88+2 (class - character)

The desired result would be 90 (class - integer)

I tried to create a function in order to transform such multiple columns

add_fun <- function(x){
  a <- strsplit(x, "\\+")

  for (i in 1:length(a)){
    a[[i]] <- as.numeric(a[[i]])
  }

  for (i in 1:length(a)){
    a[[i]] <- a[[i]][1] + a[[i]][2]
  }

  x <- as.numeric(unlist(a))
}

This works perfectly fine when I manually transform each column but the function won't return the desired results. Can someone sort this out?

  • 2
    you forgot `return(x)` at the end of the function. – JBGruber Jan 21 '19 at 17:54
  • @JBGruber Thanks for the reply but it still doesn't work. The x part remains the same in the data frame – Aishwarya Sharma Jan 21 '19 at 18:00
  • Can you post a sample data column. – Amit Gupta Jan 21 '19 at 18:02
  • Without any data or error message it is hard to say anything else. Look [here](https://stackoverflow.com/a/5963610/5028841) for some guidance. – JBGruber Jan 21 '19 at 18:09
  • I run your function and add `return(x)`, and it works on my computer. – Darren Tsai Jan 21 '19 at 18:24
  • Hi everyone Thanks for your help. I've added the data source. The columns I want to transform are ST LS RS LW etc – Aishwarya Sharma Jan 21 '19 at 18:26
  • The values remain unchanged for x despite that I have edited the function as x <- return(as.numeric(unlist(a)) – Aishwarya Sharma Jan 21 '19 at 18:30
  • Your syntax is wrong. Just put `return(x)` under `x <- as.numeric(unlist(a))`. – Darren Tsai Jan 21 '19 at 18:34
  • Can you be clear what the "desired result" is? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Show us how exactly you are calling this function. Functions return new values; they typically don't update values outside the function due to the scoping rules of functional programming languages. – MrFlick Jan 21 '19 at 19:49

1 Answers1

1

read the csv data in df then extract the 4 columns required using

dff <- df[, c("LS","ST", "RS","LW")]

def_fun <- function(x){
  a <- strsplit(x, '\\+')
  for (i in length(a)){
    b <- sum(as.numeric(a[[i]]))
  }
  return (b)
}

Then apply the operations on the required columns

for (i in 1: ncol(dff)){
  dff[i] <- apply(dff[i], 1, FUN = def_fun)
}

You can cbind this dataFrame with the original one and drop the original columns.

I hope it proves helpful.

Amit Gupta
  • 2,698
  • 4
  • 24
  • 37