[R] Problem with filling dataframe's column

javad bayat j@b@y@t194 @end|ng |rom gm@||@com
Sun Jun 11 23:54:52 CEST 2023


Dear Rui;
Many thanks for your email. I used one of your codes,
"data2$LU[which(data2$Layer == "Level 12")] <- "Park"", and it works
correctly for me.
Actually I need to expand the codes so as to consider all "Levels" in the
"Layer" column. There are more than hundred levels in the Layer column.
If I use your provided code, I have to write it hundred of time as below:
data2$LU[which(data2$Layer == "Level 1")] <- "Park";
data2$LU[which(data2$Layer == "Level 2")] <- "Agri";
...
...
...
.
Is there any other way to expand the code in order to consider all of the
levels simultaneously? Like the below code:
data2$LU[which(data2$Layer == c("Level 1","Level 2", "Level 3", ...))] <-
c("Park", "Agri", "GS", ...)


Sincerely




On Sun, Jun 11, 2023 at 1:43 PM Rui Barradas <ruipbarradas using sapo.pt> wrote:

> Às 21:05 de 11/06/2023, javad bayat escreveu:
> > Dear R users;
> > I am trying to fill a column based on a specific value in another column
> of
> > a dataframe, but it seems there is a problem with the codes!
> > The "Layer" and the "LU" are two different columns of the dataframe.
> > How can I fix this?
> > Sincerely
> >
> >
> > for (i in 1:nrow(data2$Layer)){
> >            if (data2$Layer == "Level 12") {
> >                data2$LU == "Park"
> >                }
> >            }
> >
> >
> >
> >
> Hello,
>
> There are two bugs in your code,
>
> 1) the index i is not used in the loop
> 2) the assignment operator is `<-`, not `==`
>
>
> Here is the loop corrected.
>
> for (i in 1:nrow(data2$Layer)){
>    if (data2$Layer[i] == "Level 12") {
>      data2$LU[i] <- "Park"
>    }
> }
>
>
>
> But R is a vectorized language, the following two ways are the idiomac
> ways of doing what you want to do.
>
>
>
> i <- data2$Layer == "Level 12"
> data2$LU[i] <- "Park"
>
> # equivalent one-liner
> data2$LU[data2$Layer == "Level 12"] <- "Park"
>
>
>
> If there are NA's in data2$Layer it's probably safer to use ?which() in
> the logical index, to have a numeric one.
>
>
>
> i <- which(data2$Layer == "Level 12")
> data2$LU[i] <- "Park"
>
> # equivalent one-liner
> data2$LU[which(data2$Layer == "Level 12")] <- "Park"
>
>
> Hope this helps,
>
> Rui Barradas
>


-- 
Best Regards
Javad Bayat
M.Sc. Environment Engineering
Alternative Mail: bayat194 using yahoo.com

	[[alternative HTML version deleted]]



More information about the R-help mailing list