简体   繁体   English

R“错误:if中出现意外符号”

[英]R “Error: unexpected symbol in if”

For the life of me, I can't find an answer online to my very basic problem trying to execute an if statement. 在我的一生中,我无法在线上尝试执行if语句的最基本问题找到答案。 Any help greatly appreciated. 任何帮助,不胜感激。

data: 数据:

Id,mo.year,
123,201102
436,201101
129,201302

(Both variables are character) (两个变量都是字符)

Code: 码:

if(data$mo.year IN('201101','201102')) {data$year=1}

Results in: 结果是:

Error: unexpected symbol in "if (data$mo.year IN"

if(data$mo.year IN('201201','201202')) {data$year=2}
if(data$mo.year IN('201301','201302')) {data$year=3}

Yields same errors. 产生相同的错误。

Suggestions as to what I'm missing? 关于我所缺少的建议?

Thanks! 谢谢!

It looks like you just need ifelse , the vectorized version of an if statement: 看起来您只需要ifelse ,即if语句的向量化版本:

Df <- data.frame(
  Id=c('123','436','129'),
  mo.year=c('201102','201101','201302'),
  stringsAsFactors=FALSE)
##
Df$year <- ifelse(
  Df$mo.year %in% c('201101','201102'),
  1,
  ifelse(
    Df$mo.year %in% c('201201','201202'),
    2,3))
##
> Df
   Id mo.year year
1 123  201102    1
2 436  201101    1
3 129  201302    3

Assuming you are just using the fourth digit of the mo.year column to generate your value, you could also do something like this, which is a little more concise: 假设您只是使用mo.year列的第四位数字来生成您的值,那么您还可以执行以下操作,这更加简洁:

Df$year <- as.numeric(
  gsub(
    "(201)(\\d)(\\d+)","\\2",Df$mo.year))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM