使用模式匹配在R数据帧中创建新列

时间:2015-04-10 16:28:23

标签: regex r dplyr

我正在尝试基于使用模式匹配的现有列创建新列。现有列是用户代理字段,例如

“Mozilla / 5.0(iPad; U; CPU OS 3_2,如Mac OS X; en-us)AppleWebKit / 531.21.10(KHTML,类似Gecko)版本/ 4.0.4 Mobile / 7B367 Safari / 531.21.10”< / p>

我想创建一个使用模式匹配来识别设备的新列。

- 如果user_agent喜欢'%iPad%'而user_agent喜欢'%WebKit%',那么设备就是iPad。 -if用户代理user_agent喜欢'%Android%'而user_agent不喜欢'%Mobile%'那么设备是一个android - 如果(user_agent喜欢'%Silk%'和user_agent喜欢'%WebKit%')那么设备是点燃的 -if(user_agent喜欢'%Playbook%')然后设备是其他

我想尝试在dplyr中使用mutate函数来创建新列,但需要有关如何构造正则表达式的帮助

即mutate(data,device = ....)

1 个答案:

答案 0 :(得分:2)

这样的东西?

x <- c("Mozilla/5.0 (iPad; stuff AppleWebKit more stuff",
        "Android",
        "stuff Silk more stuff and WebKit",
        "stuff Playbook more stuff", 
        "unknown")

y <- ifelse(grepl("iPad", x) & grepl("WebKit", x), "iPad", 
        ifelse(grepl("Android", x) & !grepl("Mobile", x), "android", 
                ifelse(grepl("Silk", x) & grepl("WebKit", x), "kindle", 
                        ifelse(grepl("Playbook", x), "other", 
                                "don't know")
                )
        )
)

data.frame(x, y)
                                                x          y
1 Mozilla/5.0 (iPad; stuff AppleWebKit more stuff       iPad
2                                         Android    android
3                stuff Silk more stuff and WebKit     kindle
4                       stuff Playbook more stuff      other
5                                         unknown don't know

修改

或者这可能更容易:

device <- rep(NA_character_, length(x))

device[grepl("iPad", x) & grepl("WebKit", x)] <-  "iPad"
device[grepl("Android", x) & !grepl("Mobile", x)] <-  "android"
device[grepl("Silk", x) & grepl("WebKit", x)] <-  "kindle"
device[grepl("Playbook", x)] <-  "other"

data.frame(x, device)

                                                x  device
1 Mozilla/5.0 (iPad; stuff AppleWebKit more stuff    iPad
2                                         Android android
3                stuff Silk more stuff and WebKit  kindle
4                       stuff Playbook more stuff   other
5                                         unknown    <NA>