【问题标题】:Delete empty elements in vector and create vector with only data删除向量中的空元素并创建仅包含数据的向量
【发布时间】:2020-09-30 10:45:33
【问题描述】:

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

有什么好办法吗?

【问题讨论】:

  • R 是矢量化的,所以这里不需要循环。像这样的东西应该适合你:withspace[[1]][withspace[[1]] != ""]
  • 还有,应该是for(i in withspace[[1]])
  • 非常感谢!我已经拉了几个小时的头发,现在它起作用了!

标签: r for-loop if-statement vector


【解决方案1】:

我同意 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]] 的相应元素的副本。

【讨论】:

  • 而不是提取两次,可能是v1 &lt;- withspace[[1]]; v1[v1 != '']会减少重复
  • 是的,我做了 withspace[[1]][withspace[[1]] != ""] 并且成功了。我不熟悉 R,并且更习惯于使用 for 循环来遍历每个向量,所以这是非常有用的信息。我又在做类似的事情,你的观察正是我所需要的,所以谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-11-12
  • 2020-05-22
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多