>我有一个向量,它有空元素,然后是一些我无法预测索引的数据。我只想删除所有空元素并只留下一个包含数据的向量。我不能只是尝试用数据拉动索引,因为数据量可能会有所不同并显示在不同的索引中(我是从 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是一个初始化的空向量。这是空间的样子:
[[1]]
[1] "City" "" "" "" "" ""
[7] "" "" "" "" "" ""
[13] "" "" "" "" "" ""
[19] "" " Province" "" "" "" ""
[25] "" "" "" "" "" ""
[31] "" "" "" " Postal"
有没有好方法可以做到这一点?
我同意Dave2e的观点:
withspace[[1]][withspace[[1]] != ""]
应该做这个伎俩。
还有几点观察:
循环循环遍历
withspace[[1]]
的向量元素,但在循环中将其视为索引。如果需要索引,则需要将循环定义为for (i in 1:length(withspace[[1]]))
。whithspace
显然是一个列表或数据框。然而,感兴趣的载体是withspace[[1]]
.但是在你的循环中,你循环访问顶级(列表(元素。您必须将循环设置为for (i in withspace[[1]])
。在这种情况下,withspace[[1]][i]
在循环中没有意义。您必须直接解决i
,这是withspace[[1]]
相应元素的副本。