R Error in do_one(nmeth) : NA/NaN/Inf in foreign function call (arg 1) (2 Examples)

In this post, I’ll show how to deal with the “Error in do_one(nmeth) : NA/NaN/Inf in foreign function call (arg 1)” in the R programming language.

Creating Example Data

set.seed(2987465)                   # Example vector in R
my_vec <- as.character(c("aaa", round(runif(100), 2)))
head(my_vec)                        # First values of example vector
# [1] "aaa"  "0.38" "0.1"  "0.06" "0.54" "0.96"

Example 1: Replicating the Error Message in do_one(nmeth) : NA/NaN/Inf in foreign function call (arg 1)

kmeans(my_vec, 3)                   # kmeans function leads to error
# Error in do_one(nmeth) : NA/NaN/Inf in foreign function call (arg 1)
# In addition: Warning message:
# In storage.mode(x) <- "double" : NAs introduced by coercion

Example 2: Solving the Error Message in do_one(nmeth) : NA/NaN/Inf in foreign function call (arg 1)

my_vec <- as.numeric(my_vec)        # Convert vector to numeric
# Warning message:
# NAs introduced by coercion
my_vec <- my_vec[!is.na(my_vec)]    # Remove NA values from vector
head(my_vec)                        # Head of updated vector
# [1] 0.38 0.10 0.06 0.54 0.96 0.94
kmeans(my_vec, 3)                   # kmeans functions works properly
# K-means clustering with 3 clusters of sizes 34, 23, 43
# 
# Cluster means:
#        [,1]
# 1 0.8200000
# 2 0.1156522
# 3 0.4139535
# 
# Clustering vector:
#   [1] 3 2 2 3 1 1 3 1 3 3 1 2 1 1 2 3 1 2 2 3 1 1 2 2 2 3 1 3 2 3 1 1 1 3 3 2 1 2 3 1 1 1 2 2 1 3 3 2 1 3 3 3 3 1 3 1 3 3 2 1 1 3 3 3 1 2 1 1 3 1 3 3 2 1 3 3 2 3 3 3 2 3 3 1 3 3 2 3 1 3 3 2 3 3 1 1 1 3 1 2
# 
# Within cluster sum of squares by cluster:
# [1] 0.5642000 0.1147652 0.4558279
#  (between_SS / total_SS =  86.3 %)
# 
# Available components:
# 
# [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss" "betweenss"    "size"         "iter"         "ifault"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top