Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

r - add_column applies to a matrix

I have a 2-by-2 tibble, and use add_column to add a 2-by-2 matrix. I want to have a resulting 4-by-4 tibble, but it ends up with a 2-by-3 tibble.

Here is a sample code:

A <- tibble( x = c(-1,1), y = c(-2,2))

A <- A %>% add_column( z = matrix( rnorm(4), 2,2 )   )

and dim(A) returns 2 3.

So my question is how this resulting matrix can be 2-by-4?

question from:https://stackoverflow.com/questions/66054555/add-column-applies-to-a-matrix

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe you can try

> A %>% add_column(as_tibble(matrix(rnorm(4), 2, 2)))
# A tibble: 2 x 4
      x     y     V1     V2
  <dbl> <dbl>  <dbl>  <dbl>
1    -1    -2 -0.647 -0.982
2     1     2 -0.264 -1.25

If you want to add columns with names starting with z, we can use

A %>% add_column(setNames(as_tibble(matrix(rnorm(4), 2, 2)),paste0("z",1:2)))

or (thank akrun's comment)

A %>% add_column(as_tibble(matrix(rnorm(4), 2, 2, dimnames = list(NULL, c('z1', 'z2')))))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...