Home > Software design >  Assigning names and types to the columns of an empty data frame
Assigning names and types to the columns of an empty data frame

Time:10-05

I found the following command to create an empty data frame whose columns have a name and a type:

dataFrameMio = data.frame("col1" = character(0), "col2" = numeric(0), "col3"= numeric(0))

class(dataFrameMio$col1)  # character OK
class(dataFrameMio$col2)  # numeric OK
class(dataFrameMio$col3)  # numeric OK

And I found this code where the type is automatically set to logical. Is it possible to specify the type also in this case?

colonne = c("col4", "col5", "col6")
dataFrameMio2 = data.frame((matrix(nrow = 0, ncol = length(colonne))))
colnames(dataFrameMio2) = colonne
print(dataFrameMio2)

class(dataFrameMio2$col4)  # logical
class(dataFrameMio2$col5)  # logical
class(dataFrameMio2$col6)  # logical

CodePudding user response:

It is just that matrix cannot have more than one type. It may be either better to create a list and wrap to data.frame as list can have multiple types. Or if we want to change the type

dataFrameMio2[] <- Map(`class<-`, dataFrameMio2, 
   c("character", "numeric", "numeric"))

-checking

> str(dataFrameMio2)
'data.frame':   0 obs. of  3 variables:
 $ col4: chr 
 $ col5: num 
 $ col6: num 
> class(dataFrameMio2$col4)
[1] "character"
> class(dataFrameMio2$col5)
[1] "numeric"
> class(dataFrameMio2$col6)
[1] "numeric"
  • Related