2016-12-16 160 views
1

我有一個名爲DF數據幀映射使用正則表達式的值:你怎麼R中

dput(df) 
structure(list(Agent = structure(c(3L, 1L, 2L), .Label = c("[email protected]", 
"[email protected]", "[email protected]"), class = "factor"), 
    Server = structure(c(3L, 1L, 2L), .Label = c("domain01", 
    "namesrv200", "proddb101"), class = "factor")), .Names = c("Agent", 
"Server"), class = "data.frame", row.names = c(NA, -3L)) 

有一種叫做應用程序,包含值向量:

dput(app) 
c("db", "dm", "ns") 

我需要添加另一個列調用df調用應用程序,並將與代理列匹配的應用程序值插入到應用程序值中。下面是最終的結果DF1:

dput(df1) 
structure(list(Agent = structure(c(3L, 1L, 2L), .Label = c("[email protected]", 
"[email protected]", "[email protected]"), class = "factor"), 
    Server = structure(c(3L, 1L, 2L), .Label = c("domain01", 
    "namesrv200", "proddb101"), class = "factor"), App = structure(1:3, .Label = c("db", 
    "dm", "ns"), class = "factor")), .Names = c("Agent", "Server", 
"App"), row.names = c(NA, -3L), class = "data.frame") 

我怎麼能R中做到這一點,在DF創建一個列並插入值與應用價值相匹配代理列?

+0

你真的沒有指定的匹配應該是怎樣發生的事情。 – joran

+0

@joran,如果應用程序在df $代理中,將該應用程序值添加到df中的匹配行作爲新條目 – user1471980

+0

我認爲您的示例數據也是錯誤的,'prodb101 @ webserver101'可能會顛倒過來。 –

回答

2

你可以做

app <- c("db", "dm", "ns") 
names(app) <- c("proddb101", "domain01", "namesrv200") 
df$App <- app[as.character(df$Server)] 
df 
#     Agent  Server App 
# 1 [email protected] proddb101 db 
# 2 [email protected] domain01 dm 
# 3 [email protected] namesrv200 ns 

其中proddb101被映射到db等。 as.character是必要的,因爲df$Serverfactor類型。

或者,如果你想更普遍匹配,你可以

app <- c("db", "dm", "ns") 
vgrepl <- Vectorize(grepl, "pattern") 
m <- vgrepl(app, df$Agent, fixed = TRUE) 
df$App <- colnames(m)[max.col(m, "first")] # assign first match 
df 
#     Agent  Server App 
# 1 [email protected] proddb101 db 
# 2 [email protected] domain01 dm 
# 3 [email protected] namesrv200 ns 
+0

這不會工作。我不知道哪個服務器映射到應用程序。我需要能夠在df $ Agent中搜索應用程序,如果匹配,然後添加它。 – user1471980

+0

看看我的編輯。你的問題的標題,例子和描述有點模棱兩可。 – lukeA

+0

謝謝你的工作。 – user1471980