1

我有一个由元素及其评级组成的矩阵,例如

matrix(data=c("A","B","C",NA,0.7,0.5,0,NA,"D","E","F","G",0.9,0.4,0.2,0.005),nrow=4,byrow=FALSE)

    [,1] [,2]  [,3] [,4]   
[1,] "A"  "0.7" "D"  "0.9"  
[2,] "B"  "0.5" "E"  "0.4"  
[3,] "C"  "0"   "F"  "0.2"  
[4,] NA   NA    "G"  "0.005"

我想用 NA 替换所有小于 0.1 的评级(以及它们旁边的元素)。

例如

matrix(data=c("A","B",NA,NA,0.7,0.5,NA,NA,"D","E","F",NA,0.9,0.4,0.2,NA),nrow=4, byrow=FALSE)

    [,1] [,2]  [,3] [,4]  
[1,] "A"  "0.7" "D"  "0.9"  
[2,] "B"  "0.5" "E"  "0.4"  
[3,] NA   NA    "F"  "0.2"  
[4,] NA   NA    NA   NA    

当我认为必须有更好的方法时,我正要在一个大的 for 循环中执行此操作。任何建议将不胜感激。

4

2 回答 2

1

在您的示例中,“C”转到 NA。我认为这是一个错误,所以我没有复制它。

mat <- matrix(data=c("A","B","C",NA,0.7,0.5,0,NA,"D","E","F","G",0.9,0.4,0.2,0.005),nrow=4,byrow=FALSE)
mat[mat < 0.1] <- NA

此外,如果您真正存储元素及其评级,也许 data.frame 会是更好的选择:

> data.frame(element=toupper(letters[1:7]), rating=c(0.7,0.5,0,0.9,0.4,0.2,0.005))
   element  rating
1        A   0.700
2        B   0.500
3        C   0.000
4        D   0.900
5        E   0.400
6        F   0.200
7        G   0.005

然后,您可以使用以下命令创建这些值及其整行 NA:

> df[df[,"rating"] < 0.1,] <- NA
> df
  element rating
1       A    0.7
2       B    0.5
3    <NA>     NA
4       D    0.9
5       E    0.4
6       F    0.2
7    <NA>     NA

最后,这是将矩阵转换为 data.frame 的方法

elements <- as.vector(mat[,seq(from=1, to=ncol(mat),by=2)])
ratings <- as.vector(mat[,seq(from=2, to=ncol(mat),by=2)])
df <- data.frame(element=elements,rating=ratings)
于 2013-01-30T15:28:51.890 回答
0

我同意其他人。最好将矩阵用于数字,将 data.frame 用于不同的 tpes 列。

您并不清楚元素 < 0.1 旁边的元素是什么意思,但可以从相邻(左)的评论字符中理解。

这是我的解决方案。我将您的矩阵转换为向量以进行简单索引,然后将其再次转换为矩阵。

mat <- matrix(data=c("A","B","C", NA,
                     0.7,0.5,0,NA,
                     "D","E","F","G",
                     0.9,0.4,0.2,0.005),
                     nrow=4,byrow=FALSE)
dim(mat) <- NULL
mat[c(which(mat<0.1)-4,which(mat<0.1))] <- NA
matrix(mat,nrow=4,byrow=F)

   [,1] [,2]  [,3] [,4] 
[1,] "A"  "0.7" "D"  "0.9"
[2,] "B"  "0.5" "E"  "0.4"
[3,] NA   NA    "F"  "0.2"
[4,] NA   NA    NA   NA  
于 2013-01-30T16:13:08.840 回答