Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Code works but then fails when I try to turn it into a function (R)

I’m trying to create a function that will take in a table of data, convert it into a df, change the row names into a separate column, then delete the row names (else the row names will appear twice), and then rearrange the columns.

I can get this to work outside of a function but as soon as I put it into a function it doesn’t work.

Example data:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

tb <- matrix(rep(2, times=8), ncol=2, byrow=TRUE)
tb <- as.table(tb)

Getting the desired result without creating a function:

n <- as.data.frame.matrix(tb)   
n$Variable <- row.names(n)   #Make new column containing row names. Call it Variable.
row.names(n) <- NULL   #Get rid of row names (otherwise the row names will appear twice)
n <- n[,c("Variable", "A", "B")]  #Rearrange columns 

Attempting to do the same as above but make it into a function:
(I get this far and then realize the output is not what I expected. I would expect df with an additional column containing the row names at this stage. Instead, I just get the row names being printed)

dataframe_function<-function(data) {
  n <- as.data.frame.matrix(data)
  n$Variables <- row.names(n)
  #rownames(n) <- NULL
}

df1 <- dataframe_function(tb)
df1

Tried various things but can’t work out where I’m going wrong and can’t find a solution online. Can anyone help, please?

>Solution :

The function is incomplete. Below is all of the code previously not in a function.

dataframe_function <- function(data) {
  n <- as.data.frame.matrix(data)
  n$Variable <- row.names(n)
  row.names(n) <- NULL
  n[, c("Variable", "A", "B")]  #Rearrange columns
}

tb <- matrix(rep(2, times=8), ncol=2, byrow=TRUE)
tb <- as.table(tb)

df1 <- dataframe_function(tb)
df1
#>   Variable A B
#> 1        A 2 2
#> 2        B 2 2
#> 3        C 2 2
#> 4        D 2 2

Created on 2023-01-01 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading