【发布时间】:2015-03-08 02:05:19
【问题描述】:
如何使用dplyr 简化或执行以下操作:
-
对所有
data.frame名称运行函数,例如mutate_each(funs())用于值,例如names(iris) <- make.names(names(iris)) -
删除不存在的列(即不删除任何内容),例如
iris %>% select(-matches("Width")) # ok iris %>% select(-matches("X")) # returns empty data.frame, why? -
按名称(字符串)添加新列,例如
iris %>% mutate_("newcol" = 0) # ok x <- "newcol" iris %>% mutate_(x = 0) # adds a column with name "x" instead of "newcol" -
重命名一个不存在的data.frame colname
names(iris)[names(iris)=="X"] <- "Y" iris %>% rename(sl=Sepal.Length) # ok iris %>% rename(Y=X) # error, instead of no change
【问题讨论】:
-
第三个为什么不呢?
iris %>% mutate_( 'x' = 0) -
@BondedDust,添加一个名为“x”的列,而他们希望将其命名为“newcol”或存储 n x 的任何名称。
-
x <- "Sepal.Length"; iris %>% rename_(.dots = setNames(x,"sl"))有效,但不能用于 (4),因为缺少 colnames 会引发错误 -
看起来 iris %>% select(-matches("X")) 现在返回完整的 iris data.frame。不再需要下面答案中的一切参数。