当前位置:  开发笔记 > 编程语言 > 正文

R:更简单的方法将矩阵列表中的0更改为NA?

如何解决《R:更简单的方法将矩阵列表中的0更改为NA?》经验,为你挑选了1个好方法。

我想将列表矩阵中的所有0转换为NA.我想出了如何完成这项任务的方法.但是,它太复杂了,我认为应该有一个简单的方法来做到这一点.这里有一些示例数据:

ABlue <- list("111.2012"=matrix(c(1, 0, 6, 0, 1, 0),
                            nrow = 1, byrow = T),
          "112.2012"=matrix(c(6, 2, 2, 0, 3, 1),
                            nrow = 1, byrow = T),
          "111.2011"=matrix(c(3, 2, 0, 0, 1, 9),
                            nrow = 1, byrow = T),
          "112.2011"=matrix(c(1, 2, 0, 0, 7, 0),
                            nrow = 1, byrow = T))
CNTRYs <- c("USA", "GER", "UK", "IT", "CND", "FRA")
ABlue <- lapply(ABlue  , "colnames<-",  CNTRYs ) # gets names from Country list

重要的是,原始矩阵已经将国家/地区名称作为名称,因此与此列表(ABlue)匹配会很不错.

这是我现在使用的方式:

ABlue.df<-data.frame(do.call("rbind",ABlue)) # two step approach to replace 0 with NA according to: "http://stackoverflow.com/questions/22870198/is-there-a-more-efficient-way-to-replace-null-with-na-in-a-list"
ABlue.df.withNA <- sapply(ABlue.df, function(x) ifelse(x == 0, NA, x))
ABlueNA <- split(ABlue.df.withNA, 1:NROW(ABlue.df.withNA)) # is again a list (of vectors)  
names(ABlueNA) <- names(ABlue) # list with old names
ABlueNAdf <- lapply(ABlueNA, function(x) as.data.frame(x)) # turned into list of dfs of one column
ABlueNAdfT <- lapply(ABlueNAdf, function(x) t(x)) # transponed to list of dfs of one row and 206 cols
ABlueNAdfTnam <- lapply(ABlueNAdfT  , "colnames<-",  CNTRYs ) # gets names from Country list
ABlueNAdfTnam <- lapply(ABlueNAdfTnam  , "rownames<-",  1:NROW(ABlueNAdfTnam[1]) )
ABlue2 <- ABlueNAdfTnam

想法如何减少线条和复杂性?谢谢

编辑:我想拥有与原始数据相同的结构!



1> A5C1D2H2I1M1..:

你可以replace像这样使用:

lapply(ABlue, function(x) replace(x, x == 0, NA))
# $`111.2012`
#      USA GER UK IT CND FRA
# [1,]   1  NA  6 NA   1  NA
# 
# $`112.2012`
#      USA GER UK IT CND FRA
# [1,]   6   2  2 NA   3   1
#
# $`111.2011`
#      USA GER UK IT CND FRA
# [1,]   3   2 NA NA   1   9
#
# $`112.2011`
#      USA GER UK IT CND FRA
# [1,]   1   2 NA NA   7  NA

或者,正如@roland建议的那样:

lapply(ABlue, function(x) {x[x == 0] <- NA; x})

或者,如果您有管道成瘾:

library(purrr)
ABlue %>% map(~ replace(.x, .x == 0, NA))


这基本上是'lapply(ABlue,function(x){x [x == 0] < - NA; x})`.
@MaratTalipov,"purrr"会更合适.
推荐阅读
喜生-Da
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有