保存.rds文件时遇'条件长度>1'错误的解决求助
解决saveRDS报错:the condition has length > 1
问题原因
报错提示说明saveRDS()的file参数传入了长度大于1的向量,根源是polygon_id的提取方式导致它不是单个标量值——当使用mypolygon[i, "TRACTCE"]提取时,返回的可能是带维度的向量(比如长度为1但保留了数据框列的结构),或者在某些循环迭代中polygon_id本身包含多个值,最终让paste0()生成了多个文件名,导致here()返回多个路径,触发saveRDS()的参数错误。
解决方案
调整polygon_id的提取方式,确保它是单个标量值,同时验证文件名生成逻辑:
1. 修改ID提取代码
将提取polygon_id的行替换为以下任意一种方式:
- 直接按位置提取标量:
polygon_id <- mypolygon[["TRACTCE"]][i] - 转换为字符类型(适用于因子列):
polygon_id <- as.character(mypolygon[i, "TRACTCE"])
2. 修改后的完整代码
# Iterate over each row in the result for (i in seq_along(inter2012)) { # Extract the indices of intersecting points for the i-th polygon indices <- unlist(inter2012[[i]]) # Extract the corresponding polygon ID as a scalar value polygon_id <- mypolygon[["TRACTCE"]][i] # Create a new dataset using the row values to subset mypoint2012 new_dataset <- mypoint2012[indices, ] # Assign a name to the dataset based on the polygon ID dataset_name <- paste0("Crimes_2012_Census_Tract_", polygon_id) # Save the new dataset saveRDS(new_dataset, here("data_prep", paste0(dataset_name, ".rds"))) }
3. 额外排查步骤
- 在循环中加入
print(length(polygon_id)),检查是否存在迭代时polygon_id长度大于1的情况,若有则需要确认inter2012与mypolygon的行数是否匹配。 - 如果
TRACTCE列是因子类型,建议先全局转换为字符:mypolygon$TRACTCE <- as.character(mypolygon$TRACTCE)
内容的提问来源于stack exchange,提问作者tim
相关产品推荐
相关产品推荐

