【发布时间】:2015-12-18 09:40:56
【问题描述】:
我想将列表矩阵中的所有 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
如何减少线条和复杂性的想法?谢谢
编辑:我希望拥有与原始数据相同的结构!
【问题讨论】: