簡體   English   中英

如何根據前一列的名稱重命名列

[英]How to rename columns based on the names of the previous column

我有一個數據框,其中包含通過抓取 web 生成的列,以獲取其中幾列具有相同名稱的信息,例如

plaintiff,attorney,defendant,attorney 
Mr. Litigious, Laywer A,Big Company,Lawyer B

看看attorney欄如何具有相同的名稱? 我可以使用janitor::clean_names使它們獨一無二,但這不是很有用:我希望根據前面的列重命名attorney列,如下例所示:

plaintiff,attorney_plaintiff,defendant,attorney_defendant
Mr. Litigious, Laywer A,Big Company,Lawyer B

目的是確定在我正在抓取的案例中誰代表誰。

經過大量搜索,我無法弄清楚做這種事情的正確方法是什么樣的。 我在 Python 中找到了這個答案,但我想知道這是否可以使用 R 來實現。

也許試試這個:

cols <- names(df)
inds <- which(duplicated(cols) | duplicated(cols, fromLast = TRUE))
names(df)[inds] <- paste( cols[inds], cols[inds - 1],sep = '_')
df

#      plaintiff attorney_plaintiff   defendant attorney_defendant
#1 Mr. Litigious           Laywer A Big Company           Lawyer B

names(df)
#[1] "plaintiff"  "attorney_plaintiff" "defendant"     "attorney_defendant"

暫無
暫無

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

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