gpt4 book ai didi

r - 在dplyr中,如何删除和重命名不存在的列,操作所有名称,并使用字符串命名新变量?

转载 作者:行者123 更新时间:2023-12-03 23:47:44 29 4
gpt4 key购买 nike

如何使用 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
  • 最佳答案

  • 我会为此使用 setNames:
  • iris %>% setNames(make.names(names(.)))
  • 包括everything() 作为select 的参数:
  • iris %>% select(-matches("Width"), everything())
    iris %>% select(-matches("X"), everything())
  • 据我所知,除了像您已经这样做的那样明确命名字符串之外,没有其他快捷方式:
  • iris %>% mutate_("newcol" = 0)

    关于r - 在dplyr中,如何删除和重命名不存在的列,操作所有名称,并使用字符串命名新变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27865865/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com