A numeric column in data.frame that returns "num" with str () but not is.numeric ()

I have data.frame, d1, which has 7 columns, the 5-7th column should be numeric:

str(d1[5])
'data.frame':   871 obs. of  1 variable:
 $ Latest.Assets..Mns.: num  14008 1483 11524 1081 2742 ... 

is.numeric(d1[5])
[1] FALSE

as.numeric(d1[5])
Error: (list) object cannot be coerced to type 'double'

How can it be? If str identifies it as numeric, how can it not be numeric? I import from CSV.

+3
source share
3 answers
> is.numeric_data.frame=function(x)all(sapply(x,is.numeric))

> is.numeric_data.frame(d1[[5]])
[1] TRUE 

Why

d1is a list, therefore d1[5]is a list of length 1, and in this case contains a data.frame. to get a data frame use d1[[5]].

Even if a data frame contains numeric data, it is not numeric:

> x = data.frame(1:5,6:10)
> is.numeric(x)
[1] FALSE

The individual columns in the data frame are either numeric or non-numeric. For instance:

> z <- data.frame(1:5,letters[1:5])

> is.numeric(z[[1]])
[1] TRUE
> is.numeric(z[[2]])
[1] FALSE

, , all sapply:

> sapply(z,is.numeric)
    X1.5 letters.1.5. 
    TRUE        FALSE 

> all(sapply(z,is.numeric))
[1] FALSE

> all(sapply(x,is.numeric))
[1] TRUE

:

> is.numeric_data.frame=function(x)all(sapply(x,is.numeric))

> is.numeric_data.frame(d1[[5]])
[1] TRUE 
+4

( ). class(d1[5])? , , d1[[5]] d1[5][[1]] .

Edit:

, d1 [5] , . - :

is.numeric(d1[5][,1])
+2

d1 [5] . (, ?) . , , . :

is.numeric(d1[5][[1]])
as.numeric(d1[5][[1]])

, , . R , , SQL, , .

This discussion of indexing from the R language definition document really helped me wrap my head around how to reference elements in R.

+2
source

Source: https://habr.com/ru/post/1729590/


All Articles