I would like to create a new object with properties similar with the below example. Although gas is df it contains three other df and in overall is classed both as list and df. As I'm tidyverse user this structure is strange to me.
data('gas', package = 'gamair')
str(gas)
R> str(gas)
'data.frame': 60 obs. of 3 variables:
$ octane: num 85.3 85.2 88.5 83.4 87.9 ...
$ NIR : 'AsIs' num [1:60, 1:401] -0.0502 -0.0442 -0.0469 -0.0467 -0.0509 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:60] "1" "2" "3" "4" ...
.. ..$ : chr [1:401] "900 nm" "902 nm" "904 nm" "906 nm" ...
$ nm : num [1:60, 1:401] 900 900 900 900 900 900 900 900 900 900 ...
Thanks
CodePudding user response:
That "AsIs" means we have to use I()
to protect data frame columns. Such protection is a must, if we want to have a matrix or a list, rather than a vector, in a data frame column.
x <- 1:4
Y <- matrix(5:12, nrow = 4, dimnames = list(LETTERS[1:4], letters[1:2]))
Z <- matrix(13:20, nrow = 4)
## wrong
wrong <- data.frame(x = x, Y = Y, Z = Z)
str(wrong)
#'data.frame': 4 obs. of 5 variables:
# $ x : int 1 2 3 4
# $ Y.a: int 5 6 7 8
# $ Y.b: int 9 10 11 12
# $ Z.1: int 13 14 15 16
# $ Z.2: int 17 18 19 20
## correct
correct <- data.frame(x = x, Y = I(Y), Z = I(Z))
str(correct)
#'data.frame': 4 obs. of 3 variables:
# $ x: int 1 2 3 4
# $ Y: 'AsIs' int [1:4, 1:2] 5 6 7 8 9 10 11 12
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : chr [1:4] "A" "B" "C" "D"
# .. ..$ : chr [1:2] "a" "b"
# $ Z: 'AsIs' int [1:4, 1:2] 13 14 15 16 17 18 19 20