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;
Desired output:
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
答案 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