使用R嵌套的IfElse语句比较两个变量字符串

时间:2015-05-15 05:43:23

标签: r string csv if-statement printing

示例输入数据(存储在工作目录中的csv中):

EMPLID,From_DeptCode,FromDept,To_DeptCode,To_Dept,TransactionTypeCode,TransactionType,EffectiveDate,ChangeType
0239583290,21,Sales,43,CustomerService,10,Promotion,12/12/2012
1230495829,21,Sales,21,Sales,10,Promotion,9/1/2013
4059503918,93,Operations,93,Operations,13,Demotion,11/18/2014
3040593021,19,Headquarters,23,International,11,Reorg,12/13/2011
7029406920,15,Marketing,84,Development,19,Reassignment,1/5/2010
2039052819,19,Headquarters,19,Headquarters,10,Promotion,4/15/2015

代码:

Transfers <- read.csv(file="Transfers.csv", head=TRUE, sep=",",colClasses=c(NA,NA,NA,NA,NA,NA,NA,"Date",NA))

Transfers$ChangeType <- ifelse(Transfers$From_DeptCode == Transfers$To_DeptCode, "No Change", ifelse(Transfers$TransactionType == "Reorg", "Reorg", "Transfer")) 

Transfers2 <- subset(Transfers, ChangeType != "No Change")

print(Transfers2)

预期产出:

EMPLID,From_DeptCode,FromDept,To_DeptCode,To_Dept,TransactionTypeCode,TransactionType,EffectiveDate,ChangeType
0239583290,21,Sales,43,CustomerService,10,Promotion,12/12/2012,Transfer
3040593021,19,Headquarters,23,International,11,Reorg,12/13/2011,Reorg
7029406920,15,Marketing,84,Development,19,Reassignment,1/5/2010,Transfer

实际值:

> print(Transfers2)
Error in print(Transfers2) : object 'Transfers2' not found

不知道为什么会这样。

1 个答案:

答案 0 :(得分:-1)

所以我发现了我的问题..

为了使我的代码能够工作,我不得不将光标放在每个代码块的行的末尾,并按顺序单独运行它们。

我正跳到脚本底部并将光标放在最后一行代码下面并运行它并得到错误。

为什么我需要在光标本身中一次运行一个代码块?