【发布时间】: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