简体   繁体   中英

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. 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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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