[R] Problem with filling dataframe's column

@vi@e@gross m@iii@g oii gm@ii@com @vi@e@gross m@iii@g oii gm@ii@com
Sun Jun 11 16:58:30 CEST 2023


The problem being discussed is really a common operation that R handles
quite easily in many ways.

The code shown has way too many things that do not fit to make much sense
and is not written the way many R programmers would write it.

Loops like the one used are legal but not needed. 

As has been noted, use of "==" for assignment is the wrong choice. Not using
some method to refer to a specific cell  would still result in odd behavior.


One accepted and common method s to do this vectorized as you are dealing
with two vectors of the same size.

Code like:

Matches <- Data2$Layer == "Level 12"

Will result in a Boolean vector containing TRUE where it found a match,
FALSE otherwise.

Now you can use the above as a sort of indexing as in:

data2$LU[Matches] <- "Park"

Only the indexes marked TRUE will be selected and set to the new value.

Of course, the two lines can be combined as:

data2$LU[Data2$Layer == "Level 12"] <- "Park"

There are also alternatives where people use functions like ifelse() also in
base R.

And, of course, some people like alternate packages such as in the Tidyverse
where you might have used a mutate() or other methods.

-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of javad bayat
Sent: Sunday, June 11, 2023 4:05 PM
To: R-help using r-project.org
Subject: [R] Problem with filling dataframe's column

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"
              }
          }




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

	[[alternative HTML version deleted]]

______________________________________________
R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
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