[R] Modifying a data.frame

Jeffrey Spies jspies at virginia.edu
Sun Oct 3 12:14:18 CEST 2010


You should examine what is being looped over when you use a for loop
with the "i in dataframe" syntax:

j<-1; for(i in ex){ cat('step', j, i, sep=" ", fill=T); j<-j+1}

As you can see, each column in ex is being set to i for each step of
the for loop.  Instead, it seems that you want to step over every
row--a change made in the first line:

for (i in 1:dim(ex)[1]) {
    if(ex[i,3]=="A"|| ex[i,3]=="C"){
        ex[i,4]<- -9999
    }else {
        ex[i,4]<-10
    }
}

1:dim(ex)[1] is then a vector of row index values that is looped over.

A more R-ish version of this might be:

ex[,4] <- ifelse(ex$eff == 'A' | ex$eff == 'C', -9999, 10)

I'm not sure this is the case, but if -9999 is supposed to represent
missingness, missing values are represented by `NA`s in R.

ex[,4] <- ifelse(ex$eff == 'A' | ex$eff == 'C', NA, 10)

?NA for more info.  Note: those are not single quotes, but instead back-ticks.

Hope that helps,

Jeff.

On Sun, Oct 3, 2010 at 4:58 AM, Bapst Beat <Beat.Bapst at braunvieh.ch> wrote:
>  Hello list members
>
> I have a problem with modifying a data.frame.
> As an example given is a data.frame called ex :
>
>
> ex<-data.frame(id=c(1,2,3,4,5,6),obs=c(14,9,20,36,55,47),eff=c("A","A","B","C","C","C"))
>
>
> After that I would like to modify the object ex with the following short script:
>
>
> for (i in ex) {
>
> if(ex[i,3]=="A"|| ex[i,3]=="C"){
>
> ex[i,4]<--9999
>
> }
>
> else {
>
> ex[i,4]<-10
>
> }
>
> }
>
> This script is creating an error message:
>
> Fehler in if (ex[i, 3] == "A" || ex[i, 3] == "C") { :
>  Fehlender Wert, wo TRUE/FALSE nötig ist
>
>
> Why this script  doesn't  work properly?
>
> Thanks a lot for your hints
>
> Beat
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list