【问题标题】:Combination of named vectors命名向量的组合
【发布时间】:2015-04-25 11:03:42
【问题描述】:

我已经命名了我想组合的向量,如下所示:

v1 <- c(0,1,2,3)
v2 <- c(0,1,2,3)
v3 <- c(0,1,2,3)
names(v1) <- c("This","is","an","example")
names(v2) <- c("This","great","value","random")
names(v3) <- c("This","This","and","This")

v1 和 v2 的预期结果:

This is an example great value random
0    1  2  3       1     2     3

对于 v1 和 v3:

This is an example This and This
0    1  2  3       1    2   3

如您所见,如果名称不同,向量只是绑定在一起。如果在结果向量中出现多次该名称,则如果对应的值相同,则保留一次,但如果每次出现的值不同,则保留多次。 我不知道我是否明确了我想要实现的目标。

有办法实现这样的目标吗? 谢谢

【问题讨论】:

    标签: r vector


    【解决方案1】:

    我会做一个辅助函数,像这样:

    Combiner <- function(vec1, vec2, vecOut = TRUE) {
      temp <- unique(rbind(data.frame(as.table(vec1)),
                           data.frame(as.table(vec2))))
      if (isTRUE(vecOut)) setNames(temp$Freq, temp$Var1)
      else temp
    }
    

    重点是比较名称和值,我发现将其放入data.frame 的形式中最简单。

    然后用法是:

    Combiner(v1, v2)
    #    This      is      an example   great   value  random 
    #       0       1       2       3       1       2       3 
    Combiner(v1, v3)
    #    This      is      an example    This     and    This 
    #       0       1       2       3       1       2       3 
    

    对于任意数量的向量,您可以将函数修改为:

    Combiner <- function(..., vecOut = TRUE) {
      dots <- list(...)
      if (any(is.null(sapply(dots, names)))) stop("All vectors must be named")
      temp <- unique(do.call(rbind, lapply(dots, function(x) {
        data.frame(Name = names(x), Value = unname(x), stringsAsFactors = FALSE)
      })))
      if (isTRUE(vecOut)) setNames(temp$Value, temp$Name)
      else temp
    }
    

    虽然第一个版本仅适用于数字命名向量(因为它使用as.table),但第二个版本也应该适用于命名字符向量。

    【讨论】:

    • 好的,它适用于示例数据 - 到目前为止一切都很好。在我的真实数据上,生成的都是相同的,但类型是字符而不是数字,我收到以下错误:Error in unique(rbind(data.frame(as.table(vec1)), data.frame(as.table(vec2)))) : error in evaluating the argument 'x' in selecting a method for function 'unique': Error in as.table.default(vec2) : cannot coerce to a table
    • @MineSweeper,不确定。我刚刚更新了帖子末尾的“组合器”功能,不使用table。你可以试试那个版本吗?
    • 与第二个版本完美兼容(我必须删除isTRUE)谢谢;)
    • @MineSweeper,没问题。很高兴能提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-05-12
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多