Error in fun(x[[i]], …) : only defined on a data frame with all numeric-alike variables

The error message “error in fun(x[[i]], …) : only defined on a data frame with all numeric-alike variables” indicates that a function is expecting a data frame with only numeric variables, but the input is not meeting this requirement. In other words, the function can only be applied to data frames that contain only numeric columns.

Here’s an example to illustrate this error:

# Create a data frame with both numeric and non-numeric variables
df <- data.frame(var1 = c(1, 2, 3),
                 var2 = c("a", "b", "c"),
                 var3 = c(TRUE, FALSE, TRUE))

# Apply a function that only works with numeric data frames
result <- some_function(df)

In the above example, the some_function is expecting a data frame with only numeric columns. However, the df data frame contains both numeric (var1) and non-numeric (var2, var3) variables, leading to the mentioned error.

To resolve this issue, ensure that your data frame only contains numeric variables. If you have non-numeric variables that are not relevant for the analysis, you can remove them using the subset function or by selecting only the numeric columns using the select_if function from the dplyr package:

# Remove non-numeric variables using subset
numeric_df <- subset(df, select = sapply(df, is.numeric))

# Select only numeric variables using dplyr
library(dplyr)
numeric_df <- select_if(df, is.numeric)

After making sure your data frame only contains numeric variables, you can apply the function without encountering the mentioned error.

Similar post

Leave a comment