变量不替换R中循环中的值
这就是我想做的:变量不替换R中循环中的值,r,loops,variables,R,Loops,Variables,这就是我想做的: 我有一个大的excel表格,我正在导入到R 数据需要清理,因此其中一个步骤是测试字符长度 一旦程序发现一个过长的字符串,它需要提示操作员进行替换 操作员输入一个备选方案,程序用输入文本替换原始方案 我的代码似乎是按程序运行的,但我的变量没有覆盖原始值 library(tidyr) library(dplyr) library(janitor) library(readxl) fileToOpen <-read_excel(file.choose(),sheet="
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)}
结果为空,但如果我运行
MasterFile$Field_to_Check[MasterFile$Field_to_Check == "Some Text that's in the data frame"]
结果出来了。你知道为什么我不能用变量过滤这个列表吗?测试变量的结果与预期一致。使用
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
}
CPNErrors 26)
对于(我在CPN中){
var=readline(粘贴0(“替换”,主文件$Field_to_Check[i],“使用什么?”)
MasterFile$Field_to_Check[i]谢谢,但这不起作用。它确实分配了变量,但与我的其他代码一样,它实际上并没有替换原始数据框中的坏数据。:(@J.Alexander当我在自己的样本数据框上检查我的答案时,它对我有效。你能用dput(head(MasterFile,10))提供数据样本吗
让我在你的数据集上测试答案吗?天哪。我不知道我第一次做错了什么——我把代码删除,重新启动并使用了你的代码块,它工作得很好。真是太感谢你了!!
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
}