-1

I am trying to standardize feedback from an API in R. However in some cases, the API returns a different format. This does not allow me to standardize and automate. I have thought of a solution which is as follows:

  1. if dataframe has more than 1 variable, keep dataframe as it is
  2. if dataframe has 1 variable then transpose

this id what I tried till now

col <- ncol(df)
df <- ifelse( col > 1, as.data.frame(df), as.data.frame(t(df))

This however returns a list and does not allow the process further. Thank you for the help in advance. any links would help too.

Thanks

Sotos
  • 51,121
  • 6
  • 32
  • 66
marine8115
  • 588
  • 3
  • 22

1 Answers1

1

Maybe you need something like this:

# some simple dataframes
df1 <- data.frame(col1 = c("a","b"))

df2 <- data.frame(col1 = c("a","b"),
                  col2 = c("c","d"))

func <- function(df) {
                      if (ncol(df) ==1) {
                                         as.data.frame(t(df))
                                        } else {
                                         (df)
                                        }
                      }

 func(df1)
     V1 V2
col1  a  b
 func(df2)
  col1 col2
1    a    c
2    b    d
s__
  • 9,270
  • 3
  • 27
  • 45