简体   繁体   中英

Is there a way to create a column in a data frame conditioned to a join not bringing this column from another file because it had 0 rows?

I have to join 2 data frames ( clients and check_error ), where the second one in the left join ( check_error ) will bring a column with the value "1" for all the rows.

Then, after the join, if this column ( error201 in the example) is NA, I'll assign the value "0". If not, the value "1" (which was the original value of it).

check_error<- anti_join(sclients,sproducts, by= c("cod_pro"), na_matches = "never")

check_error$error201 <- "1"

clients<-  left_join(clients, check_error, by= c("cod_pro"), na_matches = "never")
clients$erro201 <- ifelse(is.na(clients$error201), "0", "1")

But when I create the data frame check_error using the antijoin, I got 0 rows.

Because of that, when I assign the value "1" to check_error$error201 , I got the following error message:

Error in `$<-.data.frame`(`*tmp*`, error201, value = "1") : 
  replacement has 1 row, data has 0

For that reason, the ifelse at the end of the example also results in an error message, similar to the above:

Error in `$<-.data.frame`(`*tmp*`, error201, value = logical(0)) : 
  replacement has 0 rows, data has 128083 

And so I get to my title question: is it possible for me to create clients$error201 if the left join "fails" because check_error has 0 rows?

Sorry if the question is not properly elaborated. English in not my first language. And thanks in advance to all who takes some of their time to read this.

EDIT:

After I posted the question, thought on a possible solution. Maybe create the column on data frame clients prior to the joins, asssigning "0". This way, when I do a join, I would have error201.x and error201.y. When the join "fails" because the result is zero rows, I would be left with the column with the "0"s assign. Is this correct?

EDIT 2: About the EDIT 1, in this case the error201.x was never created, since there is no error201 in y file (because it has 0 rows). :(

Found a simple solution by counting the rows of the check_error file, creating the column in clients if the result is 0.

Now that I figured it out, the question sound so silly.

if (nrow(check_error) == 0){
    clients$error201 <- "0"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM