【发布时间】:2019-01-08 22:45:58
【问题描述】:
case_when 没有产生预期的结果:
我的清单:
library(tidyverse)
1:6%>%
str_c('var',.)%>%
map(~assign(.,runif(30,20,100),envir=globalenv()))
tibble<-as_tibble(
bind_cols(mget(ls(pattern='*v')))
)
cluster<-kmeans(tibble,centers=3)
cluster
tibble$kmeans<-as.factor(cluster[['cluster']])
mylist<-split(tibble,tibble$kmeans)
names(mylist)<-str_c('dataset',seq_along(mylist))
我的代码:
variables<-str_c('var',1:6)
mylist%>%
map(~mutate_at(.,.vars=vars(variables),
.funs=funs(.=case_when(
.%in%c(1:50)~'less',
.%in%c(51:100)~'more'
))))
输出将NAs 生成新变量,而不是less 或more。这个函数有什么问题?
【问题讨论】:
-
str_c, map, assign, as_tibble, bind_cols, mget, ls... 为什么不使用 base:data.frame(matrix(runif(30 * 6, 20, 100), ncol = 6))