Home > Software design >  Ifelse function for dataframe in R
Ifelse function for dataframe in R

Time:09-19

I have a dataframe in R. Either the df has two columns with values, or it has the dimensions 0,0. If the dataframe has columns with values, I want to keep these values, but if the dimensions are 0,0, I want to create two columns with one row containing 0,0 values. Either it looks like this:

    start = c (2, 10, 20)
    end = c(5, 15, 25)
    dataframe = as.data.frame (cbind (start, end))

-> if the df looks like this, it should be retained

Or like this:

start = c ()
end = c()
dataframe = as.data.frame (cbind (start, end))

-> if the df looks like this, a row with (0,0) should be added in the first row.

I tried ifelse

dataframe_new = ifelse (nrow(dataframe) == 0, cbind (start = 0,end =0) , dataframe)

But if the dataframe is not empty, it remains only the value of the first row and column. If the dataframe is empty, there is only one 0.

CodePudding user response:

Instead of the function ifelse, you should be using if...else clauses here. ifelse is used when you want to create a vector whose elements vary conditionally according to a logical vector with the same length as the output vector. That's not what you have here, but rather a simple branching condition (if the data frame has zero rows do one thing, if not then do something else). This is when you use if(condition) {do something} else {do another thing}

If you need to use the code a lot, you could save yourself time by putting it in a simple function:

fill_empty <- function(x) {
 if(nrow(x) == 0) data.frame(start = 0, end = 0) else x
}

Let's test this on your examples:

start = c (2, 10, 20)
end = c(5, 15, 25)
dataframe = as.data.frame (cbind (start, end))

fill_empty(dataframe)
#>   start end
#> 1     2   5
#> 2    10  15
#> 3    20  25

And

start = c ()
end = c()
dataframe = as.data.frame (cbind (start, end))

fill_empty(dataframe)
#>   start end
#> 1     0   0

Created on 2022-09-19 with reprex v2.0.2

  • Related