我有一个命名向量:
dput(model_object$regression_feature_importance_matrix)
c(spend_7d = 0.704766041126329, d7_utility_sum = 0.168417670114147,
recent_utility_ratio = 0.101030461314979, IOS = 0.0096061893294683,
is_publisher_organic = 0.008247148545793, is_publisher_facebook = 0.0079324895692841
看起来像这样:
model_object$regression_feature_importance_matrix
spend_7d d7_utility_sum recent_utility_ratio IOS is_publisher_organic is_publisher_facebook
0.704766041 0.168417670 0.101030461 0.009606189 0.008247149 0.007932490
我想将其转置并制成数据框。我可以这样:
model_object$regression_feature_importance_matrix %>% bind_rows() %>% t() %>% data.frame() %>% rownames_to_column() %>% rename(Feature = rowname)
Feature .
1 spend_7d 0.704766041
2 d7_utility_sum 0.168417670
3 recent_utility_ratio 0.101030461
4 IOS 0.009606189
5 is_publisher_organic 0.008247149
6 is_publisher_facebook 0.007932490
1)是否有更优雅,更短的方法? model_object$regression_feature_importance_matrix %>% bind_rows() %>% t() %>% data.frame() %>% rownames_to_column()
我只是想像大概是将命名向量转换为df会很常见,我想知道是否有一种现成的方式?
2)我试图重命名:
工作正常:model_object$regression_feature_importance_matrix %>% bind_rows() %>% t() %>% data.frame() %>% rownames_to_column() %>% rename(Feature = rowname)
不起作用:
model_object$regression_feature_importance_matrix %>% bind_rows() %>% t() %>% data.frame() %>% rownames_to_column() %>% rename(Feature = rowname, Gain = .)
Error in rename(Feature = rowname, Gain = .) : object 'rowname' not found
我想我知道为什么。点表示在管道运算符中传递的上一个对象,而我想引用列名以便更改它。如何更改列名“。”在同一个dplyr管道中“获得”收益?与仅names(df) <- c('Features', 'Gain')
答案 0 :(得分:1)
我们还可以使用stack
将命名向量转换为数据帧,然后使用rename_all
stack(x)[2:1] %>% dplyr::rename_all(~c("Feature","Gain"))
# Feature Gain
#1 spend_7d 0.704766041
#2 d7_utility_sum 0.168417670
#3 recent_utility_ratio 0.101030461
#4 IOS 0.009606189
#5 is_publisher_organic 0.008247149
#6 is_publisher_facebook 0.007932490
数据
x <- c(spend_7d = 0.704766041126329, d7_utility_sum = 0.168417670114147,
recent_utility_ratio = 0.101030461314979, IOS = 0.0096061893294683,
is_publisher_organic = 0.008247148545793, is_publisher_facebook = 0.0079324895692841)