开发者

Recode / rename data within a dataframe while grep is used to selected certain variables

In my dataframe I select only variables test3-test8

data[,grep('(test[3-8]+$)',names(data)),]

Now I want to replace "1" with "2". According to df[ df == "1" ]开发者_如何学编程 = "2" I tried:

data[,grep('(test[3-8]+$)',names(data)),][ data[,grep('(test[3-8]+$)',names(data)),] == "1" ] = "2"

That didn't work.

Error in [<-.data.frame(*tmp*, , grep("(^dv_beh_[0-9]+r)", names(data)), : unused argument(s) ()

What is my mistake?


Eliminate the superfluous commas (which are specifying options to the data frame, but you list no options) and the error goes away:

dtf <- data.frame(test1=runif(10))
dtf <- cbind(dtf,dtf)
dtf <- cbind(dtf,dtf)
dtf[3,3] <- 1
names(dtf) <- paste("test",seq(ncol(dtf)),sep="")
names.sel <- grep('(test[3-8]+$)',names(dtf))
dtf[,names.sel][ dtf[,names.sel] == 1 ] <- 2
stopifnot(dtf[3,3]==2)

And to prove that that's the problem, I can reproduce the error with:

data[,names.sel,][ data[,names.sel] == 1 ,] <- 2
Error in `[<-.data.frame`(`*tmp*`, , grep("(test[3-8]+$)", names(data)),  : 
  unused argument(s) ()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜