【问题标题】:Replace with 0 when retrieving data from a matrix从矩阵中检索数据时替换为 0
【发布时间】:2019-05-23 00:11:43
【问题描述】:

我正在从矩阵中存在的值中填充数据框中的列的值。该值的搜索是从名为e1e2 的两列中执行的。但有可能在这些列中的任何一个中都包含矩阵中不存在的字符串。这当然会出错,但我想知道是否可以继续用 0 填充不存在的值。

x<-cbind(c(0.3,0.35,0.35,0),c(0.2,0.2,0.4,0.2)
,c(0,0.6,0.1,0.3),c(0.5,0.25,0.25,0))
colnames(x) <- c("A","B","C","D")
rownames(x) <- c("A","B","C","D")

y<-as.data.frame(cbind(c(1,2,3,4,5,6)
,c("A","A","B","A","B","A"),c("D","C","C","D","D","J")))
colnames(y) <- c("id","e1","e2")

index_df = y%>% select(e1,e2)
colnames(index_df)<-c('rows','cols')

y$l<-x[as.matrix(index_df)]

x[as.matrix(index_df)] 中的错误:下标越界

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    我们可以将match 的行名和列名xe1e2y 的列一起使用,然后使用它来对来自x 的值进行子集化。

    y$l <- x[cbind(match(y$e1, rownames(x)), match(y$e2, colnames(x)))]
    
    y
    #  id e1 e2    l
    #1  1  A  D 0.50
    #2  2  A  C 0.00
    #3  3  B  C 0.60
    #4  4  A  D 0.50
    #5  5  B  D 0.25
    #6  6  A  J   NA
    

    这将为不匹配的值返回NA,如果需要,可以通过执行将其更改为0

    y$l[is.na(y$l)] <- 0
    

    【讨论】:

      【解决方案2】:

      我们需要根据%in% 值的出现来创建索引。这里,“J”不是“x”的列名。因此,使用“i1”,我们创建了一个逻辑索引并只更新那些列名与“e2”匹配的行。现在,我们可以直接使用 OP 的语法了

      i1 <- index_df$cols %in% colnames(x)
      y$l[i1] <- x[as.matrix(index_df[i1,])]
      y
      #  id e1 e2    l
      #1  1  A  D 0.50
      #2  2  A  C 0.00
      #3  3  B  C 0.60
      #4  4  A  D 0.50
      #5  5  B  D 0.25
      #6  6  A  J   NA
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-15
        • 1970-01-01
        • 1970-01-01
        • 2021-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多