[英]Create a new data.frame with "AsIs" elements
I would like to create a new object with properties similar to the example below.我想创建一个具有类似于下面示例的属性的新对象。
Although gas is a data frame, it contains "matrix" like columns with "AsIs" type.虽然 gas 是一个数据框,但它包含像“AsIs”类型的列一样的“矩阵”。
As I am a tidyverse
user, this structure is strange to me.由于我是
tidyverse
用户,因此这种结构对我来说很奇怪。
data('gas', package = 'gamair')
str(gas)
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 ...
That "AsIs" means we have to use I()
to protect data frame columns. “AsIs”意味着我们必须使用
I()
来保护数据框列。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.