簡體   English   中英

Dataframe,根據多因子列的組,將單列中的行倒序

[英]Dataframe, reverse order of rows in one single column according to groups of multiple factor columns

我正在嘗試按組反轉 dataframe 的一列的行,其中分組由多個因子列驅動。

我想從這里撥打 go

在此處輸入圖像描述

我想根據選定的組反轉 Col5 的數值,以獲得:

在此處輸入圖像描述

所有其他列都是因素

我嘗試使用此代碼,但失敗了

reord<-a %>% dplyr::group_by(Col1,Col2,Col4)%>% dplyr::mutate(reve=rev(Col5))

你有什么建議嗎? 非常感謝任何幫助提前致謝

做好了。

這是我的解決方案(也使用了一些來自論壇的代碼,所以還是謝謝)。

split<-a %>% ##a is the original dataframe
       group_split(Col1, Col2, Col4) ## the dataframe is subset to tibble


split1<-lapply(split, function(x) dplyr::mutate(x, reve=rev(Col5))) ## rev() is applied to all columns of interest of the list

reord1<-bind_rows(split1, .id = 'id') ## the list objects are rbound to obtain the dataframe with either original values in Col5 and reverse values in the new column "reve"

效果很好

暫無
暫無

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

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