【问题标题】:Variable not replacing value in loop in R变量不替换R中循环中的值
【发布时间】:2021-08-01 11:23:48
【问题描述】:

这就是我想要做的:

  1. 我有一个大型 Excel 工作表要导入 R。
  2. 需要清理数据,因此其中一个过程是测试字符长度。
  3. 一旦程序发现字符串过长,需要提示操作者替换
  4. 操作员输入一个替代项,程序用输入的文本替换原来的。

我的代码似乎在程序上工作,但我拥有的变量没有覆盖原始值。

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 变量按预期出现。

【问题讨论】:

    标签: r loops variables


    【解决方案1】:

    使用for 循环尝试这种方法:

    CPNErrors <- which(nchar(MasterFile$Field_to_Check) > 26)
    
    for(i in CPNErrors){
      var=readline(paste0("Replace ",MasterFile$Field_to_Check[i]," with what? "))
      MasterFile$Field_to_Check[i] <- var
    }
    

    【讨论】:

    • 谢谢,但这不起作用。它确实分配了变量,但就像我的其他代码一样,它实际上并没有替换原始数据框中的坏数据。 :(
    • @J.Alexander 当我检查我自己的示例数据框的答案时,它对我有用。您能否通过dput(head(MasterFile, 10)) 提供您的数据样本,以便我在您的数据集上测试答案?
    • 天哪。我不知道我第一次做错了什么——我把代码夷为平地,重新启动并使用你的代码块,它就像一个魅力。真是太感谢你了!!
    猜你喜欢
    • 2015-03-22
    • 2018-05-12
    • 2021-07-03
    • 2012-08-28
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多