r - 删除向量中的空元素并创建仅包含数据的向量
问题描述
我有一个包含空元素的向量,然后是其中一些我无法预测其索引的数据。我只想删除所有空元素并留下一个只包含数据的向量。我不能只是尝试用数据提取索引,因为数据量可能会有所不同并显示在不同的索引中(我是从 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"
有没有好的方法来做到这一点?
解决方案
我同意 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]]
。
推荐阅读
- java - Java Cipher AES 不加密整个字符串
- php - 如何根据 php 中另一个下拉列表中的选择创建下拉列表?
- regex - 如何通过忽略特殊字符来比较两列?
- python - 堆叠条形图交换 x 轴和 y 轴
- mysql - 加入两个 Woocommerce 表
- c# - Nhibernate 无法编译映射文件
- sql - SQL Server - where 子句的 CASE
- javascript - 选择所有复选框不调用每个复选框的 JS 函数
- symfony - 无休止的页面加载从 symfony 中的存储库(学说)获取数据
- python - 编写 BIG pandas DataFrame 的最快方法