我有一个向量,里面有空的元素,还有一些数据,我无法预测它的指数。我只想删除所有的空元素,只留下一个包含数据的向量。我不能仅仅尝试用数据来提取索引,因为数据量可能会有所不同,并显示在不同的索引上(我是从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
wospace是存储所有数据点的矩阵,wospace是一个初始化的空向量。这就是有空间的样子:
[[1]]
[1] "City" "" "" "" "" ""
[7] "" "" "" "" "" ""
[13] "" "" "" "" "" ""
[19] "" " Province" "" "" "" ""
[25] "" "" "" "" "" ""
[31] "" "" "" " Postal"
有什么好办法吗?
发布于 2020-06-10 14:00:36
我同意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]
在循环中没有意义。您必须直接寻址withspace[[1]]
.的相应元素的i
,这是一个副本。
https://stackoverflow.com/questions/62313397
复制