首页 > 解决方案 > 删除向量中的空元素并创建仅包含数据的向量

问题描述

我有一个包含空元素的向量,然后是其中一些我无法预测其索引的数据。我只想删除所有空元素并留下一个只包含数据的向量。我不能只是尝试用数据提取索引,因为数据量可能会有所不同并显示在不同的索引中(我是从 pdf 中提取的)。

我尝试创建一个 for 循环来检查元素是否为空,然后将其存储在单独的向量中:

n <- 1
for (i in withspace) {
  if (withspace[[1]][i] != "") {
    wospace[n] <- withspace[[1]][i]
    n <- n + 1
  }
}

但我不断收到这样的错误:

Error in if (withspace[[1]][i] != "") { : 
  missing value where TRUE/FALSE needed
In addition: Warning message:
In if (withspace[[1]][i] != "") { :
  the condition has length > 1 and only the first element will be used

withspace 是存储所有数据点的矩阵,wospace 是一个初始化的空向量。这就是 withspace 的样子:

[[1]]
 [1] "City"      ""          ""          ""          ""          ""         
 [7] ""          ""          ""          ""          ""          ""         
[13] ""          ""          ""          ""          ""          ""         
[19] ""          " Province" ""          ""          ""          ""         
[25] ""          ""          ""          ""          ""          ""         
[31] ""          ""          ""          " Postal" 

有没有好的方法来做到这一点?

标签: rfor-loopif-statementvector

解决方案


我同意 Dave2e:

withspace[[1]][withspace[[1]] != ""]

应该做的伎俩。

还有一些观察:

  1. 您的循环循环遍历向量元素,withspace[[1]]但在循环内您将其视为索引。如果需要索引,则需要将循环定义为for (i in 1:length(withspace[[1]])).

  2. whithspace显然是一个列表或数据框。然而,感兴趣的向量是withspace[[1]]。但是在您的循环中,您会遍历顶级(列表)元素。您必须将循环设置为for (i in withspace[[1]]). 在这种情况下,withspace[[1]][i]循环内部没有意义。您必须i直接寻址,它是 的相应元素的副本withspace[[1]]


推荐阅读