【问题标题】:Replacing columns names using a data frame in r使用 r 中的数据框替换列名
【发布时间】:2012-07-16 03:58:14
【问题描述】:

我有矩阵

m <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE,dimnames = list(c("s1", "s2", "s3"),c("tom", "dick","bob")))

   tom dick bob
s1   1    2   3
s2   4    5   6
s3   7    8   9

#and the data frame

current<-c("tom", "dick","harry","bob")
replacement<-c("x","y","z","b")
df<-data.frame(current,replacement)

  current replacement
1     tom           x
2    dick           y
3   harry           z
4     bob           b

#I need to replace the existing names i.e. df$current with df$replacement if 
#colnames(m) are equal to df$current thereby producing the following matrix


m <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE,dimnames = list(c("s1", "s2", "s3"),c("x", "y","b")))

   x y b
s1 1 2 3
s2 4 5 6
s3 7 8 9

有什么建议吗?我应该使用“if”循环吗?谢谢。

【问题讨论】:

  • +1,示例代码的好问题。

标签: r matrix dataframe


【解决方案1】:

您可以使用whichm 中的colnamesdf$current 中的值匹配。然后,当您拥有索引时,您可以从 df$replacement 子集替换 colnames。

colnames(m) = df$replacement[which(df$current %in% colnames(m))]

在上面:

  1. %in% 测试 TRUEFALSE 是否匹配被比较的对象。
  2. which(df$current %in% colnames(m)) 标识匹配名称的索引(在本例中为行号)。
  3. df$replacement[...] 是对列 df$replacement 进行子集化的基本方法,仅返回与步骤 2 匹配的行。

【讨论】:

  • 您能否就这一班轮的工作原理提供更多解释?这将使 R 初学者更具可读性。
  • @PaulHiemstra,添加了一个解释——不确定它是否是最好的。请随时改进或提供建议。
【解决方案2】:

查找索引的更直接的方法是使用match

> id <- match(colnames(m), df$current)
> id
[1] 1 2 4
> colnames(m) <- df$replacement[id]
> m
   x y b
s1 1 2 3
s2 4 5 6
s3 7 8 9

如下所述,%in% 通常使用起来更直观,效率差异很小,除非集合相对较大,例如

> n <- 50000 # size of full vector
> m <- 10000 # size of subset
> query <- paste("A", sort(sample(1:n, m)))
> names <- paste("A", 1:n)
> all.equal(which(names %in% query), match(query, names))
[1] TRUE
> library(rbenchmark)
> benchmark(which(names %in% query))
                     test replications elapsed relative user.self sys.self user.child sys.child
1 which(names %in% query)          100   0.267        1     0.268        0          0         0
> benchmark(match(query, names))
                 test replications elapsed relative user.self sys.self user.child sys.child
1 match(query, names)          100   0.172        1     0.172        0          0         0

【讨论】:

  • +1 -- %in%match 非常相似。我的偏好通常是which%in%,因为它更容易让我记住,因为它的内容类似于:“这些值df$current)中的哪个是in 这些其他值 (colnames(m)." 对于match,我总是倾向于使用相同的格式并以NAs 结尾。我不知道是否有任何无论如何,性能问题。
  • 你说得对,%in% 更直观,因此总体上更好用,?match 提供了更多关于优缺点的信息。对于我们中间的极客,我会添加一些时间!
猜你喜欢
  • 2016-10-25
  • 2017-07-29
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
  • 2020-08-01
相关资源
最近更新 更多