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

时间:2015-12-18 09:40:56

标签: r list na

我想将列表矩阵中的所有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

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

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

2 个答案:

答案 0 :(得分:17)

您可以使用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))

答案 1 :(得分:0)

我们也可以使用for

for (i in 1:length(ABlue)) {
  ABlue[[i]][ABlue[[i]]==0] <- NA
}

ABlue
# $`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

我想知道除了lapplyfor之外,我们还有其他任何功能来迭代列表。