0

I have a dataframe as follows:

##DUMMY DATAFRAME
text = c("This is neutral") 
Col2 = 0
Col3 = 0
Col4 = 0
Col5 = 0
Col6 = 0
Col7 = 0
Col8 = 0
Col9 = 0
Col10 = 0
Col11 = 0
Col12 = 0
Col13 = 0
Col14 = 0
Col15 = 0
Col16 = 0
df = data.frame(text, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)

df

             text Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 Col10 Col11 Col12 Col13 Col14 Col15 Col16
1 This is neutral    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0

I want to check the length of a list and if the length = 0, return the dataframe above, if not return a different dataframe. What happens is that it only takes the first element, not the entire dataframe.

new_df <- ifelse(length(example_of_empty_list) == 0, df, different_df)

This output will only give me

[[1]]
[1] This is neutral
Levels: This is neutral

I want my output to rather be then entire dataframe rather than the first element.

How would I go about doing this?

nak5120
  • 4,089
  • 4
  • 35
  • 94
  • 3
    `ifelse()` is vectorized, it tests a vector and returns a vector of the same length. You want to test a single condition and return a data frame, so use `if(condition) {df} else {different_df}`. – Gregor Thomas Aug 10 '17 at 16:57
  • 1
    Suggested dupe [How is `ifelse` different than `if(){} else{}`?](https://stackoverflow.com/q/9449184/903061) – Gregor Thomas Aug 10 '17 at 17:00
  • Also see `?ifelse` which begins "*`ifelse` returns a value with the same shape as `test`*". Your data frames are not "the same shape" as your `test` (a 1-element logical vector), so `ifelse` won't work. – Gregor Thomas Aug 10 '17 at 17:02
  • Thank you Gregor, that worked! – nak5120 Aug 10 '17 at 17:42

0 Answers0