gpt4 book ai didi

r - 如何处理非标准列名(空格、标点符号、数字开头)

转载 作者:行者123 更新时间:2023-12-03 06:14:18 29 4
gpt4 key购买 nike

df <- structure(list(`a a` = 1:3, `a b` = 2:4), .Names = c("a a", "a b"
), row.names = c(NA, -3L), class = "data.frame")

数据看起来像

  a a a b
1 1 2
2 2 3
3 3 4

以下调用选择

select(df, 'a a')

给出

Error in abs(ind[ind < 0]) : 
non-numeric argument to mathematical function

如何使用 select 选择“a a”和/或将其重命名为没有空格的名称?我知道以下方法:

  1. names(df)[1] <- "a"
  2. select(df, a=1)
  3. select(df, ends_with("a"))

但是如果我正在处理大型数据集,在不知道索引号或类似列名称的情况下如何获得精确匹配?

最佳答案

您可以使用反引号`选择变量。

select(df, `a a`)
# a a
# 1 1
# 2 2
# 3 3

但是,如果您的主要目标是重命名列,则可以在 plyr 包中使用 rename,其中您可以同时使用 ""``

rename(df, replace = c("a a" = "a"))
rename(df, replace = c(`a a` = "a"))

或者在base R中:

names(df)[names(df) == "a a"] <- "a"

有关使用各种引号的更详细说明,请参阅?Quotes。 “名称和标识符”部分在这里特别相关:

other [syntactically invalid] names can be used provided they are quoted. The preferred quote is the backtick".

另请参阅 ?make.names 了解有效名称。

另请参阅this post关于在 dplyr

中重命名

关于r - 如何处理非标准列名(空格、标点符号、数字开头),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22842232/

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