簡體   English   中英

如何將數據框傳遞給函數,並返回重新排列列的新數據框?

[英]How do I pass a data frame to a function, and return a new data frame with the columns rearranged?

我有這個MRA_DF數據幀。 我想將此數據框傳遞給名為AccountMRA的函數。 從這里開始,我想刪除MRA_DF $ speed列,將MRA_DF $ price列作為第一列,並將MRA_DF $ dist作為第二列。 然后我想回復這個。 我無法弄清楚這一點。

該數據幀= MRA_DF

    speed dist  price
1     4    2  200
2     4   10  100
3     7    4  300
4     7   22  400
5     8   16  100
6     9   10  200

理想輸出:

     price  dist
1     200 2
2     100 10
3     300 4
4     400 22
5     100 16
6     200 10

使用dplyr包,您可以創建一個可以刪除列的函數以及特定順序的列名列表:

library(dplyr)

# create dataframe
MRA_DF = data.frame(speed = c(4, 4, 7, 7, 8, 9), dist = c(2, 10, 4, 22, 16, 10), price = c(200, 100, 300, 400, 100, 200))

# AccountMRA takes in a dataframe, column order, and a column to drop
#' @param colorder --> list of column names in specific order
#' @param todrop --> column name to drop
#' @param data1 --> dataframe to manipulate
#' @return --> return formatted dataframe
AccountMRA <- function(data1, colorder = c('price', 'dist'), todrop = 'speed'){
    toreturn <- as.data.frame(data1
                        %>% dplyr::select(-eval(parse(text = todrop))))
    return(toreturn[, colorder])
}

AccountMRA(MRA_DF, colorder = c('price', 'dist'), todrop = 'speed')

# has the following output:
#   price dist
# 1   200    2
# 2   100   10
# 3   300    4
# 4   400   22
# 5   100   16
# 6   200   10

您可以使用基本R子集:

MRA_DF = data.frame(speed = c(4, 4, 7, 7, 8, 9), dist = c(2, 10, 4, 22, 16, 10), price = c(200, 100, 300, 400, 100, 200))

 df <- MRA_DF[,c("price","dist")]

# df
#  price dist
#1   200    2
#2   100   10
#3   300    4
#4   400   22
#5   100   16
#6   200   10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM