使用if函数更改矩阵中的值

时间:2013-01-30 15:19:52

标签: r

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

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的所有评级(及其旁边的元素)。

e.g。

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循环中这样做。任何建议将不胜感激。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

我和其他人在一起。最好使用矩阵表示数字,使用data.frame表示不同的tpes列。

你不准确的元素旁边的元素是什么意思&lt; 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