创建R中一个函数的参数,其输入以数字开始 [英] Creating a function in R with an argument whose inputs begin with a number

查看:127
本文介绍了创建R中一个函数的参数,其输入以数字开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不道歉,如果这已经回答了的地方,但是我找不到与它类似的问题,任何地方。

I do apologize if this has been answered somewhere but I can't find a question similar to it anywhere.

我想创建一个函数,其中的输入参数之一可以是(但不一定),它以数字开头的字符串。当我尝试运行此功能,R混淆。

I am trying to create a function where one of the input arguments could be (but isn't necessarily) a string which begins with a number. When I try to run this function, R get confused.

例如:

foo(df, 10, 5fum)

给我的错误:

错误:意外符号do_cv_class(数据,10,5fum

Error: unexpected symbol in "do_cv_class(data,10,5fum"

在我打算采取5fum并解析它变成2个参数5和功能FUM。我并不想创建一个第四个参数分离5和FUM。

In the function I plan on taking "5fum" and parsing it into 2 arguments "5" and "fum". I don't want to create a 4th argument to separate 5 and fum.

任何想法?任何帮助会很大。

Any ideas? Any help on this would great.

推荐答案

由于上述意见建议,你需要传递5fum为字符串。 presumably你想是这样的:

As the comments above suggest, you need to pass "5fum" as a string. Presumably you're thinking about something like this:

foo <- function(df, num1, str1) {
   str1_num <- as.numeric(gsub("([0-9]+)([[:alpha:]]+)","\\1",str1))
   str1_alpha <- gsub("([0-9]+)([[:alpha:]]+)","\\2",str1)
   print(str1_num)
   print(str1_alpha)
}

foo(df, 10, "5fum")
## [1] 5
## [1] "fum"

这篇关于创建R中一个函数的参数,其输入以数字开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆