简体   繁体   English

在R函数中运行多行代码

[英]Running multiple code lines in a R function

I would like to run some code lines in a function. 我想在函数中运行一些代码行。 Is there a easy way to run multiple code lines in R, so i don't need to run one code line after another? 有没有一种简单的方法可以在R中运行多行代码,所以我不需要再运行一行代码? For example like the void method in Java? 例如像Java中的void方法?

a() {
data$Item <- gsub(" Grams ", "g ", data$Item);
data$Item <- gsub("Grams ", "g ", data$Item);
data$Item <- gsub(" GRAMS ", "g ", data$Item);
data$Item <- gsub("GRAMS ", "g ", data$Item);
data$Item <- gsub("grams", "g ", data$Item);
data$Item <- gsub("Grams", "g ", data$Item);
}

If i run a() like that all commands are done but it also says -> 如果我像这样运行a(),所有命令都已完成,但它也会显示->

Error: unexpected '}' in "}"

Thanks for your help! 谢谢你的帮助!

You can simply put your string in lower case and do a single gsub() , and then deal with extra spaces with trimws() . 您可以简单地将字符串转换为小写并执行单个gsub() ,然后使用trimws()处理多余的空格。

data$Item <- gsub("grams", "g ", tolower(data$Item))

But you can make a function like this: 但是,您可以创建如下函数:

my_function <- function() {
    data$Item <<- gsub(" Grams ", "g ", data$Item)
    data$Item <<- gsub("Grams ", "g ", data$Item)
    data$Item <<- gsub(" GRAMS ", "g ", data$Item)
    data$Item <<- gsub("GRAMS ", "g ", data$Item)
    data$Item <<- gsub("grams", "g ", data$Item)
    data$Item <<- gsub("Grams", "g ", data$Item)
}
my_function()

Use the double <<- for changing the values globally, and not just inside the function. 使用双<<-全局更改值,而不仅仅是在函数内部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM