【发布时间】:2021-08-01 11:23:48
【问题描述】:
这就是我想要做的:
- 我有一个大型 Excel 工作表要导入 R。
- 需要清理数据,因此其中一个过程是测试字符长度。
- 一旦程序发现字符串过长,需要提示操作者替换
- 操作员输入一个替代项,程序用输入的文本替换原来的。
我的代码似乎在程序上工作,但我拥有的变量没有覆盖原始值。
library(tidyr)
library(dplyr)
library(janitor)
library(readxl)
fileToOpen <-read_excel(file.choose(),sheet="Data")
MasterFile <- fileToOpen
#This line checks the remaining bad strings in the column
CPNErrors <- nrow(filter(MasterFile,nchar(Field_to_Check) > 26))
#This line selects the bad field from the first in the list of strings to exceed the limit
TEST <- select(filter(MasterFile,nchar(Field_to_Check) > 26),Field_to_Check)[1,]
#This is the loop -- prompts the operator for a replacement, assigns a variable to the input and then replaces the bad value in the data frame
while (CPNErrors >= 1) {message("Replace ",TEST," with what?"); var=readline();MasterFile$Field_to_Check[MasterFile$Field_to_Check == TEST] <- var;print(var)}
提示起作用并将 readline() 分配给 var,但代码不会将原始字符串替换为变量。当我在循环外单独运行代码时,只要我输入一个确切的字符串(没有变量赋值),它就会被替换,所以我缺少一些语法上的东西。
我一直在寻找几个小时,并且刚刚开始使用 R,所以如果有人可以提供任何帮助,我将不胜感激。
编辑——好的……我想我找到了问题的根源,但我不知道如何解决它。当我跑步时
MasterFile$Field_to_Check[MasterFile$Field_to_Check == TEST]
它带有一个空结果,但如果我运行
MasterFile$Field_to_Check[MasterFile$Field_to_Check == "Some Text that's in the data frame"]
结果出来了。关于为什么我不能按变量过滤此列表的任何想法? TEST 变量按预期出现。
【问题讨论】: