python - R脚本错误{:缺少数据框上需要TRUE / FALSE的值
问题描述
我有一个看起来像这样的数据框
Name Surname Country Path
John Snow UK /Home/drive/John
BOB Anderson /Home/drive/BOB
Tim David UK /Home/drive/Tim
Wayne Green UK /Home/drive/Wayne
我编写了一个脚本,它首先检查如果country =="UK"
为真,则将 Path 从R更改"/Home/drive/"
为"/Server/files/"
using 。gsub
脚本
Pattern<-"/Home/drive/"
Replacement<- "/Server/files/"
for (i in 1:nrow(gs_catalog_Staging_123))
{
if( gs_catalog_Staging_123$country[i] == "UK" && !is.na(gs_catalog_Staging_123$country[i]))
{
gs_catalog_Staging_123$Path<- gsub(Pattern , Replacement , gs_catalog_Staging_123$Path,ignore.case=T)
}
}
我得到的输出:
Name Surname Country Path
John Snow UK /Server/files/John
*BOB Anderson /Server/files/BOB*
Tim David UK /Server/files/Tim
Wayne Green UK /Server/files/Wayne
我想要的输出
Name Surname Country Path
John Snow UK /Server/files/John
BOB Anderson /Home/drive/BOB
Tim David UK /Server/files/Tim
Wayne Green UK /Server/files/Wayne
我们可以清楚地看到 gsub 无法识别缺失值并附加该行。
解决方案
许多 R 函数都是矢量化的,因此我们可以避免此处出现循环。
# example data
df <- data.frame(
name = c("John", "Bob", "Tim", "Wayne"),
surname = c("Snow", "Ander", "David", "Green"),
country = c("UK", "", "UK", "UK"),
path = paste0("/Home/drive/", c("John", "Bob", "Tim", "Wayne")),
stringsAsFactors = FALSE
)
# fix the path
df$newpath <- ifelse(df$country=="UK" & !is.na(df$country),
gsub("/Home/drive/", "/Server/files/", df$path),
df$path)
# view result
df
name surname country path newpath
1 John Snow UK /Home/drive/John /Server/files/John
2 Bob Ander /Home/drive/Bob /Home/drive/Bob
3 Tim David UK /Home/drive/Tim /Server/files/Tim
4 Wayne Green UK /Home/drive/Wayne /Server/files/Wayne
实际上,这是您的代码的问题。每次通过循环时,您都会检查行i
,然后您会完全替换整个列。解决方法是[i]
在最后一行代码的适当位置添加:
gs_catalog_Staging_123$Path[i] <- gsub(Pattern , Replacement , gs_catalog_Staging_123$Path[i] ,ignore.case=T)
推荐阅读
- c++ - std::copy 指向易失数据的指针
- node.js - OpenShift“无法设置源密码”
- c - 如何编写 C 函数将整数翻译成英文短语?
- javascript - 需要解决 XMLHttpRequest 预检问题的方法
- univocity - Univocity 解析是否支持 java 8 日期时间类型转换(LocalDateTime)?
- mysql - 查找一列的重复项,但仅在另一列具有相同值时才返回结果
- shell - 如何在 IPython 控制台中获取 Shell 历史记录
- c++ - C++ google protobuf:如何从扩展的 FieldDescriptor 创建 MutableExtension
- windows - 如果文件夹名称包含 Unicode 字符,批处理将无法正常工作
- vue.js - 如何仅将 css 样式应用于特定的 Vue 组件及其子组件?