How to coerce a list object to type 'double'
If you want to convert all elements of a
to a single numeric vector and length(a)
is greater than 1 (OK, even if it is of length 1), you could unlist
the object first and then convert.
as.numeric(unlist(a))
# [1] 10 38 66 101 129 185 283 374
Bear in mind that there aren't any quality controls here. Also, X$Days
a mighty odd name.
coerce a list object to type double
To apply the coercion on a subset of multiple columns, lapply
is the right way. That yields a list, that you want to assign back to the subset columns.
as.numeric.factor <- function(f) as.numeric(levels(f))[f]
# as.numeric.factor <- function(f) as.numeric(as.character(f)) ## alternatively
d[,2:3] <- lapply(d[,2:3], as.numeric.factor)
str(d)
# 'data.frame': 3 obs. of 3 variables:
# $ var1: chr "ab" "ac" "ad"
# $ var2: num 1.1 2.6 0
# $ var3: num 1 5.4 0
If you want a new object you may use the lapply
with replace
.
fg <- replace(d, 2:3, lapply(d[,2:3], as.numeric.factor))
str(fg)
# 'data.frame': 3 obs. of 3 variables:
# $ var1: chr "ab" "ac" "ad"
# $ var2: num 1.1 2.6 0
# $ var3: num 1 5.4 0
Data
d <- structure(list(var1 = c("ab", "ac", "ad"), var2 = structure(c(2L,
3L, 1L), .Label = c("0", "1.1", "2.6"), class = "factor"), var3 = structure(c(2L,
3L, 1L), .Label = c("0", "1", "5.4"), class = "factor")), row.names = c(NA,
-3L), class = "data.frame")
data.frame - object cannot be coerced to type 'double'
Assuming you have all numeric columns except for the first column, you can lapply
like
data_stand[-1] <- lapply(data_stand[-1], coeff_var)
Or with dplyr
library(dplyr)
data_stand %>% mutate_if(is.numeric, coeff_var)
Error: (list) object cannot be coerced to type 'double' with multiple variables
We can do:
res<-sapply(iris[,-5], as.numeric)
attr(res,"dimnames") <- NULL
Or as @markus suggests simply:
unname(as.matrix(iris[,1:4]))
Result:
[,1] [,2] [,3] [,4]
[1,] 5.1 3.5 1.4 0.2
[2,] 4.9 3.0 1.4 0.2
[3,] 4.7 3.2 1.3 0.2
[4,] 4.6 3.1 1.5 0.2
Unusual (list) object cannot be coerced to type 'double' error when conductin KNN alogrithm
You need to use as.matrix
as I suggested in my comments above. Here's why:
str(matrix(iris,byrow=T,ncol=5))
As you can see this produces a list.
List of 5
$ : num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ : num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ : num [1:150] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
- attr(*, "dim")= int [1:2] 1 5
as.matrix
on the other hand produces a matrix.
Now why the error anyways?
From ?knn
we can see that it accepts matrices or dataframes:
train
matrix or data frame of training set cases.
test
matrix or data frame of test set cases.
A vector will be interpreted as a row vector for a single case
This explains why we have the error:
Error in knn(train, test, clas, k = kk, prob = TRUE) : (list) object cannot be coerced to type 'double'
The safe thing to do is to either use as.data.frame
or as.matrix
How to coerce a list object to type 'integer', Error in R
It looks like one of your independent variables is a string or factor variable, and all need to be numeric. See my toy dataset below. I get the same error when including all the variables; however, when I take var4 out (where variables are strings), it works).
If you want to use the variable, you could convert the string variable to a factor, then convert to the factor to a numeric variable (which will capture the underlying values of the factor).
library(naivebayes)
#data <- read.csv(file.choose(),header = T)
data <- data.frame(admit = sample(100, x=c(F,T), prob=c(.5,.5), replace=T),
var1 = sample(100, x=1:4, replace=T),
var2 = sample(100, x=1:3, replace=T),
var3 = sample(100, x=1:3, replace=T),
var4 = sample(100, x=c("s1", "s2"), replace=T))
str(data)
set.seed(1234)
splitData <- sample(2,nrow(data),replace = T,prob = c(0.8,0.2))
train<-data[splitData == 1,]
test <- data[splitData == 2,]
# Doesn't work
mdl <- naive_bayes(admit ~ .,data = train)
predicted <- predict(mdl, train, type = 'prob')
# Works
mdl <- naive_bayes(admit ~ var1 + var2 + var3,data = train)
predicted <- predict(mdl, train, type = 'prob')
# Convert string to factor then numeric
train$var4 <- as.numeric(as.factor(train$var4))
mdl <- naive_bayes(admit ~ .,data = train)
predicted <- predict(mdl, train, type = 'prob')
exact_extract throws error Error in .num_expected_args(fun) : 'list' object cannot be coerced to type 'double'
It turns out that I am just an idiot. exact_extract()
expects the functions to be quoted because they are run internally and not taken from the external functions. This solved the issue entirely:
##Loading Necessary Packages##
library(exactextractr)
library(sf)
library(spData)
library(raster)
library(tmap)
## Getting the State of Oregon from the us_states and projecting it into Oregon Statewide Lambert (EPSG 2992)
data("us_states")
OR<-st_transform(us_states[us_states$NAME=="Oregon",], st_crs("EPSG:2992"))
##Making a fake classified raster with the same extent and projection as the state of Oregon
FAKE<-raster(ext=extent(OR), res=1000, crs=crs(OR))
values(FAKE)<-sample(c(1:4), ncell(FAKE),replace=TRUE)
#Map to demonstrate that polygon overlays the raster
tmap_mode("plot")
tm_shape(FAKE)+
tm_raster()+
tm_shape(OR)+
tm_polygons(border.col="black", alpha=0)
test<-exact_extract(FAKE, OR, fun="count", summarize_df=TRUE)
Related Topics
How to Disable "Save Workspace Image" Prompt in R
Delete a Column in a Data Frame Within a List
Plot.New Has Not Been Called Yet
Reason Behind Speed of Fread in Data.Table Package in R
Typeof Returns Integer for Something That Is Clearly a Factor
R Fuzzy String Match to Return Specific Column Based on Matched String
R - Ggplot2 Issues with Date as Character for X-Axis
R Color Palettes for Many Data Classes
Unexpected 'Else' in "Else" Error
Calculate Correlation with Cor(), Only for Numerical Columns
Predict.Lm() in a Loop. Warning: Prediction from a Rank-Deficient Fit May Be Misleading
How to Install a Package from a Download Zip File
What Does "Error: Object '<Myvariable>' Not Found" Mean
How to Use Tidyr::Separate When the Number of Needed Variables Is Unknown
Read/Write Data in Libsvm Format