How to return a value from an R function with Control Structure

时间:2016-08-31 18:50:04

标签: r for-loop

I'm trying to extract the rating from a column inside a DataFrame. I have written the below function. However, the function would not stop executing and the column does not get updated.

Column values are string for example;

  • Rating R violence sexual content language
  • Rating PG-13 content language
  • ""

Desired output:

  • if the row value of the column is "" or empty than the new value should be NA
  • if the row value of the column is Rating R violence sexual content language, than the new value should be "R"
  • if the row value of the column is Rating PG-13 content language, than the new value should be "PG-13"

    C <- function (column) 
    {
      len <- length(DF$column)
    
      for (i in 1:len) 
    
      {
        a <- DF$column[i]
        b <-  unlist(strsplit(a," "))
    
      if ( length(b) == 0 ) 
      {
    
        x <-  NA
    
        DF$column[i] <- x
    
       } else ( b[1] == "Rating" & length(b) > 0 ) 
    
       DF$column[i] <- mpaaRating[2]
    
    
      } 
    }  
    
    
    DF$mpaa <- CleanMpaa(DF$mpaa)
    

Thank you

1 个答案:

答案 0 :(得分:0)

只需使用嵌套的ifelse即可。不需要循环:

DF <- data.frame(list(mpaa=c("Rating R", "Rating PG-13", "", "PG")), 
                 stringsAsFactors = FALSE)
DF
#           mpaa
# 1     Rating R
# 2 Rating PG-13
# 3              
# 4           PG

DF$clean_mpaa <- ifelse(nchar(DF$mpaa) == 0, NA, 
                        ifelse(grepl("Rating", DF$mpaa),          # FINDS PATTERN
                               gsub("Rating ", "", DF$mpaa),      # REPLACES PATTERN
                               DF$mpaa))
#           mpaa clean_mpaa
# 1     Rating R          R
# 2 Rating PG-13      PG-13
# 3                    <NA>
# 4           PG         PG