1

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
3
  • matrix can have only a single type Commented Oct 4, 2021 at 16:17
  • Hello @akrun only the logical one? Commented Oct 4, 2021 at 16:18
  • You specified nrow = 0, and thus it by default changes to logical. check matrix(nrow = 0, ncol = length(colonne)) %>% str logi[0 , 1:3] Commented Oct 4, 2021 at 16:19

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

3 Comments

if I wrote class(dataFrameMio$col4) the output is NULL instead of character. Why?
@GennaroArguzzi class for dataFrameMio2 each column gives the expected. (please check my post)
@GennaroArguzzi I think this was the issue. Earlier, I forgot the [], thus it returned a list and I didn't check it. Now corrected please check

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.