使用R中的str_plit()从定制函数中的df$VECTOR中提取向量名称 [英] Extracting vector name from df$vector in custom function with str_split() in R
本文介绍了使用R中的str_plit()从定制函数中的df$VECTOR中提取向量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试编写一个自定义函数,该函数将输入对象x中的变量名作为字符串输出,输入对象x是数据帧中的特定向量,即df$VECTOR的形式,因此它的功能如下
function(iris$Species)
>"Species"
目前我正在执行以下操作:
vector.name<-function(x){
require(stringr)
#convert df$variable into string
xname <- as.character(deparse(substitute(x)))
if (str_detect(xname,"$")==T) {
str_split(xname,"$")
}
}
但结果并不令人满意
> vector.name(iris$Species)
[[1]]
[1] "iris$Species" ""
我已经试过strsplit(){base}
和str_split(){stringr}
,它们对其他普通字母串都能正常工作,例如
> str_split(as.character(deparse(substitute(iris$Species))),"S")
[[1]]
[1] "iris$" "pecies"
如何从自定义函数中的df$vector
中提取"vector"
?
推荐答案
$
是匹配字符串末尾的元字符。转义(\$
)或将其括在方括号([$]
)中,或使用fixed
逐字计算字符
vector.name<-function(x){
xname <- as.character(deparse(substitute(x)))
if(stringr::str_detect(xname,fixed("$"))) {
stringr::str_split(xname, fixed("$"))
}
}
-测试
vector.name(iris$Species)
[[1]]
[1] "iris" "Species"
请注意,第一个str_detect
中的$
返回TRUE
,这只是一个巧合,没有其他内容,即$
本身查找字符串的末尾,并在所有字符串中匹配,无论它是否为空
> str_detect("iris$Species", "$")
[1] TRUE
> str_detect("", "$")
[1] TRUE
相反,它将是
> str_detect("iris$Species", "\$")
[1] TRUE
> str_detect("", "\$")
[1] FALSE
与str_split
类似,因为它匹配字符串的末尾,所以它返回第二个元素为空
> str_split("iris$Species", "$")
[[1]]
[1] "iris$Species" ""
这篇关于使用R中的str_plit()从定制函数中的df$VECTOR中提取向量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文