存储非NA元素的位置和值

时间:2019-02-22 05:03:35

标签: r

我有一个数据集,该数据集由具有一些NA的矩阵组成。由此,我想创建一个存储非NA值的位置和值的数据框。通过this answerwhich可用于通过tempList <- which(!is.na(dummy),TRUE)获取位置。 目前,我之后使用for循环。有没有更好的方法来添加值?

数据:

structure(c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, "#000000FF", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, "#000000FF", NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), .Dim = c(10L, 
10L))

所需结果:

structure(list(x = c(8, 7), y = c(5, 7), colour = structure(c(1L, 
1L), .Label = "#000000FF", class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))

当前代码:

tempList <- which(!is.na(dummy),TRUE)
changedDF <- data.frame(tempList[,1],tempList[,2])
names(changedDF) <- c("row","column")

for(i in 1:nrow(changedDF)){
  changedDF$colour[i] <- dummy[changedDF[i,1],changedDF[i,2]]
}

0 个答案:

没有答案