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:
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?
CodePudding user response:
How about this:
tb<-matrix(rep(2, times=8), ncol=2, byrow=TRUE)
tb<-as.table(tb)
dataframe_function<-function(data){
rn <- rownames(data)
n<-as.data.frame.matrix(data)
n$Variables<-rn
rownames(n) <- NULL
n
}
dataframe_function(tb)
#> A B Variables
#> 1 2 2 A
#> 2 2 2 B
#> 3 2 2 C
#> 4 2 2 D
Created on 2023-01-01 by the reprex package (v2.0.1)
CodePudding user response:
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