2016-12-16 100 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