【发布时间】:2018-04-12 14:16:06
【问题描述】:
这是我的数据集:
FullName <- c("Jimmy John Cephus", "Frank Chester", "Hank Chester", "Brody Buck Clyde", "Merle Rufus Roscoe Jed Quaid")
df <- data.frame(FullName)
目标:在 FullName 中查找任何空格,“”,然后提取 FirstName。
我的第一步是使用 stringr 库,因为我将使用 str_count() 和 word() 函数。
接下来我针对 df 和 R 返回测试 stringr::str_count(df$FullName, " "):
[1] 2 1 1 2 4
这是我所期望的。
接下来我测试 word() 函数:
stringr::word(df$FullName, 1)
R 返回:
[1] "Jimmy" "Frank" "Hank" "Brody" "Merle"
再一次,这正是我所期望的。
接下来我构造一个简单的 UDF(用户定义函数),其中包含 str_count() 函数:
split_firstname = function(full_name){
x <- stringr::str_count(full_name, " ")
return(x)
}
split_firstname(df$FullName)
同样,R 提供了我所期望的:
[1] 2 1 1 2 4
作为最后一步,我将 word() 函数合并到 UDF 中并为所有条件编写代码:
split_firstname = function(full_name){
x <- stringr::str_count(full_name, " ")
if(x==1){
return(stringr::word(full_name,1))
}else if(x==2){
return(paste(stringr::word(full_name,1), stringr::word(full_name,2), sep = " "))
}else if(x==4){
return(paste(stringr::word(full_name,1), stringr::word(full_name,2), stringr::word(full_name,3), stringr::word(full_name,4), sep = " "))
}
}
然后我调用 UDF 并将来自 df 的 FullName 传递给它:
split_firstname(df$FullName)
这一次我没有得到我期望的结果,R返回了:
[1] "Jimmy John" "Frank Chester" "Hank Chester" "Brody Buck" "Merle Rufus"
Warning messages:
1: In if (x == 1) { :
the condition has length > 1 and only the first element will be used
2: In if (x == 2) { :
the condition has length > 1 and only the first element will be used
我曾期望 R 会返回给我以下内容:
"Jimmy John", "Frank", "Hank", "Brody Buck", "Merle Rufus Roscoe Jed"
【问题讨论】:
-
试试这个例子来重现警告
if(1:3 == 1) "yes"。
标签: r user-defined-functions stringr