我有下面的tibble,我想从中创建第4列,这是从A,B & C的统一向量。我明白dplyr :: unite()可以做到这一点创建一个新的字符向量,但我正在寻找与载体创建一个列表列。从dplyr和rowwise的其他向量列中的新列表
现在rowwise的作品,但不保留输入的tibble。有关将A_Vector列保存到C_Vector的建议吗?
下面是代码:
library(tidyverse)
My_Data <- tibble(A_Vector = rnorm(10),
B_Vector = rnorm(10),
C_Vector = rnorm(10)) %>%
rowwise() %>%
do(Port_Weights = matrix(c(.$A_Vector,.$B_Vector,.$C_Vector),3,1))
而且结果:
Source: local data frame [10 x 1]
Groups: <by row>
# A tibble: 10 x 1
Port_Weights
* <list>
1 <dbl [3 x 1]>
2 <dbl [3 x 1]>
3 <dbl [3 x 1]>
4 <dbl [3 x 1]>
5 <dbl [3 x 1]>
6 <dbl [3 x 1]>
7 <dbl [3 x 1]>
8 <dbl [3 x 1]>
9 <dbl [3 x 1]>
10 <dbl [3 x 1]>
这不起作用:
My_Data <- tibble(A_Vector = rnorm(10),
B_Vector = rnorm(10),
C_Vector = rnorm(10)) %>%
mutate(Port_Weights = rowwise() %>% do(matrix(c(.$A_Vector,.$B_Vector,.$C_Vector),3,1)))
长的版本,这显然是没有意义的:
My_Data <- tibble(A_Vector = rnorm(10),
B_Vector = rnorm(10),
C_Vector = rnorm(10))
Data_Unite <- My_Data %>%
rowwise() %>%
do(Port_Weights = matrix(c(.$A_Vector,.$B_Vector,.$C_Vector),3,1))
My_Data <- as.tibble(cbind(My_Data,Data_Unite))
但是确实提供结果的追捧:
# A tibble: 10 x 4
A_Vector B_Vector C_Vector Port_Weights
* <dbl> <dbl> <dbl> <list>
1 -1.23504457 -0.3750408 -0.4214122 <dbl [3 x 1]>
2 -0.90678699 0.5261914 1.1191229 <dbl [3 x 1]>
3 -0.62944085 0.5995529 0.2096462 <dbl [3 x 1]>
4 2.06171633 1.5399094 2.2972950 <dbl [3 x 1]>
5 0.08761555 0.1424207 -1.4758585 <dbl [3 x 1]>
6 -1.07334432 -1.9112787 0.4820864 <dbl [3 x 1]>
7 -0.18655423 -1.3698855 0.6672621 <dbl [3 x 1]>
8 -0.97961789 -0.8194373 -0.4158516 <dbl [3 x 1]>
9 0.68112936 -1.9864507 1.0193449 <dbl [3 x 1]>
10 0.61455438 0.5885380 -1.0925312 <dbl [3 x 1]>
另外一个有趣的事情发生在很多卫星之前:https://stackoverflow.com/q/42077507/496803巧合地发现我最喜欢的问题列表,当今天寻找别的东西。 – thelatemail