在R中使用sub或gsub

时间:2013-03-10 22:27:29

标签: r gsub

我有一个档案,按年级和科目分别有问题和答案。一世 需要将路径插入到问题中。路径由 固定的网址,主题,成绩和图片名称(在问题中)。我有 能够获得构建的路径,但无法弄清楚如何使用sub 用新值替换旧值。以下是我到目前为止的情况:

 x<-read.csv( 'E:/My Documents/RED-985_second_try_2013022802.csv' , header =
 TRUE, sep = ",", fill = TRUE , quote="\"", na.strings="NA")

 ## Here we determine which rows contain a line that begins with 'img src',
 since those are the ones we want.
 target.rows <- grep(x[,3], pattern = "img src=.*\\.gif")
 new.string <- ""
 grade.string<-""
 subject.string<-""

 #Will need to look through each column by changing the value in the
 target.row command so that I bet all images

 for (i in 1: length(target.rows))
 {
    subject<-x[target.rows[i],12]
    grade<-x[target.rows[i],2]
    string.to.check <- x[target.rows[i],3]
    first.quote.pos <- gregexpr(pattern='"', string.to.check)[[1]][1] + 1
    second.quote.pos <- gregexpr(pattern='"', string.to.check)[[1]][2] - 1
    new.string[i] <- substring(string.to.check,first.quote.pos,second.quote.pos)                                                        

    if (nchar(grade) == 1)
    {
            grade<-paste(0,grade,sep="")
    }

    if (subject == 1)
    {
            subject<-"MA"
    }
    else
    {
        subject<-"RE"
    }

    grade.string[i] <-grade

    subject.string[i]<-subject

    url.string2<-sub(, paste("http://ABC.com/_practice/",
    subject,"-",grade,"/",new.string[i], sep = ""), x[[i],3])
    gsub("img src=.*\\.gif", "url.string2", x)


     }
     warnings(url.strings <- paste("http://ABC.com/_practice/",
     subject.string,"-",grade.string,"/",new.string, sep = ""))

我收到以下错误消息:

Running E:\My Documents\Revolution\Project_One\Project_One\GSUB_Try.R ...
E:\My Documents\Revolution\Project_One\Project_One\GSUB_Try.R(38): Error:
unexpected ','

我做错了什么或者我该怎么看?非常感谢你 提前。

1 个答案:

答案 0 :(得分:1)

接近结尾,你有这个:

x[[i],3]

这个逗号是出乎意料的。看一下x的早期用法,似乎你可能想要这个:

x[target.rows[i],3]