Let's assume I have this dataframe:
df <- data.frame(A = letters[1:5],
B = letters[6:10],
stringsAsFactors = FALSE)
A B
1 a f
2 b g
3 c h
4 d i
5 e j
Where I'm looking for this output:
A B
1 e j
2 d i
3 c h
4 b g
5 a f
With this function:
f_Order <- function(df){
df$Order <- as.integer(row.names(df))
df <- arrange(df, desc(Order))[,c("A","B")]
}
Though the function above doesn't work, the code inside the function works perfectly:
df$Order <- as.integer(row.names(df))
df <- arrange(df, desc(Order))[,c("A","B")]
> x
A B
1 e j
2 d i
3 c h
4 b g
5 a f
Why? How do I make the function work?
EDIT:
To clarify, the problem statement is not to change the order of the df, but to make the function f_Order
to work. The code does what I want, but it doesn't what I want inside that function. I need to know why, and how I can make the function to work.
EDIT2:
This is exactly the code I'm running, and still doesn't work any of the solutions.
x <- data.frame(A = letters[1:5],
B = letters[6:10],
stringsAsFactors = FALSE)
f_Order <- function(df){
df$Order <- as.integer(row.names(df))
df <- arrange(df, desc(Order))
return(df)
}
f_Order(x)