Mutate Works Out Of Function But Not In Function

Hi There,

I am doing some analysis for a football simulation game, and part of this involves updating some columns to numeric values as below.

combinedDataFrame = combinedDataFrame %>% rowwise() %>% mutate(attacking_crossing_adjusted = eval(parse(text = attacking_crossing)))
combinedDataFrame = combinedDataFrame %>% rowwise() %>% mutate(attacking_finishing_adjusted = eval(parse(text = attacking_finishing)))
combinedDataFrame = combinedDataFrame %>% rowwise() %>% mutate(attacking_heading_accuracy_adjusted = eval(parse(text = attacking_heading_accuracy)))
combinedDataFrame = combinedDataFrame %>% rowwise() %>% mutate(attacking_short_passing_adjusted = eval(parse(text = attacking_short_passing)))
combinedDataFrame = combinedDataFrame %>% rowwise() %>% mutate(attacking_volleys_adjusted = eval(parse(text = attacking_volleys)))

This piece of code works fine, but I have a lot of columns, so I was hoping to do something more efficient in a function.

My plan was to write the following 3 lines from the main method and call the user defined function that follows

newColumns <- (attacking_crossing_adjusted,attacking_finishing_adjusted,attacking_heading_accuracy_adjusted,attacking_short_passing_adjusted,attacking_volleys_adjusted)
oldColumns <- (attacking_crossing,attacking_finishing,attacking_heading_accuracy,attacking_short_passing,attacking_volleys)

combinedDataFrame <- makeColumnsNumeric(combinedDataFrame, oldColumns, newColumns)

makeColumnsNumeric <- function(DataFrame,nonNumericColumns,newNumericColumns)
{
lengthNonNumeric <- numeric(length = length(nonNumericColumns))

for(x in seq_along(lengthNonNumeric))
{
DataFrame = DataFrame %>% rowwise() %>% mutate(newNumericColumns = eval(parse(text = nonNumericColumns)))
}

return(DataFrame)
}

However I get the following errors.

makeColumnsNumeric <- function(DataFrame,nonNumericColumns,newNumericColumns)

  • {
  • lengthNonNumeric <- numeric(length = length(nonNumericColumns))
  • for(x in seq_along(lengthNonNumeric))
  • {
  • DataFrame = DataFrame %>% rowwise() %>%  mutate(newNumericColumns[x] = eval(parse(text = nonNumericColumns[x])))
    

Error: unexpected '=' in:
" {
DataFrame = DataFrame %>% rowwise() %>% mutate(newNumericColumns ="

}
Error: unexpected '}' in " }"

return(DataFrame)
Error: object 'DataFrame' not found

}
Error: unexpected '}' in "}"

Any ideas?

Consider using mutate_at() instead

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.