在dplyr中,如何删除和重命名不带';不存在,操纵所有名称,并使用字符串命名新变量?
如何使用在dplyr中,如何删除和重命名不带';不存在,操纵所有名称,并使用字符串命名新变量?,r,dataframe,dplyr,R,Dataframe,Dplyr,如何使用dplyr简化或执行以下操作: 对所有数据运行一个函数。frame名称,如mutate_each(funs())值,例如 names(iris) <- make.names(names(iris)) 按名称(字符串)添加新列,例如 iris%>%变异(newcol=0)#正常 x%mutate_ux(x=0)#添加名为“x”而不是“newcol”的列 重命名不存在的data.frame colname names(iris)[names(iris)=="X"] <- "
dplyr
简化或执行以下操作:
数据运行一个函数。frame
名称,如mutate_each(funs())
值,例如
names(iris) <- make.names(names(iris))
iris%>%变异(newcol=0)#正常
x%mutate_ux(x=0)#添加名为“x”而不是“newcol”的列
names(iris)[names(iris)=="X"] <- "Y"
iris %>% rename(sl=Sepal.Length) # ok
iris %>% rename(Y=X) # error, instead of no change
names(iris)[names(iris)=“X”]%重命名(sl=Sepal.Length)#ok
iris%>%重命名(Y=X)#错误,而不是没有更改
iris%>%setNames(make.names(names()))
iris%>%select(-matches(“Width”),everything())
虹膜%>%选择(-matches(“X”),everything())
iris%>%mutate_uquo(“newcol”=0)
1到3在上面得到了回答。我来这里是因为我和4号有同样的问题。以下是我的解决方案:
df <- iris
获取数据帧中列名的向量
cols <- names(name_key[!is.na(name_key)])
cols我为#4提出了以下解决方案:
最后一行当然只是为了方便输出。回答问题n.2:
如果要明确给出列的全名,可以使用函数any_of
iris %>%
select(-any_of(c("X", "Sepal.Width","Petal.Width")))
这不会删除不存在的列X,而是删除列出的其他两个列
否则,您可以使用匹配
或匹配
和匹配
的任意组合的解决方案
iris %>%
select(-any_of("X")) %>%
select(-matches("Width"))
这将显式删除X和匹配项。也可以进行多个匹配
iris %>%
select(-any_of("X")) %>%
select(-matches(c("Width", "Spec"))) # use c for multiple matches
非常感谢你!也许有人看到了3的方法,但我把它标记为解决了!DPLYR0.5.0的工作方式似乎略有不同;everything()参数将在后面添加列“宽度”。0.5.0的语法应该是:iris%>%select(-matches(“Width”)
对于数字3为什么不呢iris%>%mutate_u('x'=0)
@BondedDust,当他们希望将列命名为“newcol”或任何名称存储在nx时,添加一个名为“x”的列。x%rename_uDots=setNames(x,sl”)
可以工作,但不能用于(4),因为缺少的colnames会引发错误它看起来像iris%>%select(-matches(“x”))现在返回完整的iris data.frame。下面答案中的everything参数不再是必需的。name\u key
df <- iris
name_key <- c(
sl = "Sepal.Length",
sw = "Sepal.Width",
Y = "X"
)
for (var in names(name_key)) {
if (!(name_key[[var]] %in% names(df))) {
name_key[var] <- NA
}
}
cols <- names(name_key[!is.na(name_key)])
for (nm in names(name_key)) {
names(df)[names(df) == name_key[[nm]]] <- nm
}
df2 <- df %>%
select(cols)
iris %>%
rename_at(vars(everything()),
function(nm)
recode(nm,
Sepal.Length="sl",
Sepal.Width = "sw",
X = "Y")) %>%
head()
iris %>%
select(-any_of(c("X", "Sepal.Width","Petal.Width")))
iris %>%
select(-any_of("X")) %>%
select(-matches("Width"))
iris %>%
select(-any_of("X")) %>%
select(-matches(c("Width", "Spec"))) # use c for multiple matches