簡體   English   中英

如何基於查找表替換列中的字符串值

[英]How to replace string values in a column based on a lookup table

我有這個df。 我想根據查找表替換“ 1.1”,“ 2.1”,“ 3.2”等的每個實例。

在此處輸入圖片說明

查找表

在此處輸入圖片說明

所需的輸出

在此處輸入圖片說明

我查看了基於查找表的數據框中的替換值,但不能解決我的問題。 提前致謝!

一個選項是gsubfn 我們將一個或多個數字與一個點( [0-9.]+ )進行匹配,並在替換中傳遞從第二個數據集('df2')創建的鍵/值對list 對於帶有“鍵”的匹配模式,它將替換字符串中相應的“值”

library(gsubfn)
df1$Node <- gsubfn("([0-9.]+)", as.list(setNames(df2$Label,df2$Node)), df1$Node)
df1$Node
#[1] "One one > Two one > Three two" "One two > Two two > Three one" "One one > Two two > Three one" "One two > Two one > Three two"
#[5] "One one > Two two > Three two"

數據

df1 <- data.frame(ID = 1:5, Node = c("1.1 > 2.1 > 3.2", "1.2 > 2.2 > 3.1", "1.1 > 2.2 > 3.1", "1.2 > 2.1 > 3.2", "1.1 > 2.2 > 3.2"), stringsAsFactors = FALSE)

df2 <- data.frame(Label =  c("One one", "One two", "Two one", "Two two", "Three one", "Three two"), Node = c("1.1", "1.2", "2.1", "2.2", "3.1", "3.2"), stringsAsFactors = FALSE)

暫無
暫無

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

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