Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I am attempting to normalize the feedback from an API in R. But in some cases, the API returns a strange format. This does not allow me to normalize and automate. I have thought of a resolution which is as follows:

  1. If the dataframe has more than 1 variable, then I have to keep the dataframe as it is.
  2. If the dataframe has 1 variable, then I have to do the transpose

This is what I tried until now:

col <- ncol(df)

df <- ifelse( col > 1, as.data.frame(df), as.data.frame(t(df))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. 

1 Answer

0 votes
by (107k points)

I think you are looking for the following code:

# 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

If you are looking for the certification, then do refer to the R programming certification.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...