# [R] R function

David Carlson dcarlson at tamu.edu
Mon Jul 29 16:35:52 CEST 2013

```Rui has shown you a much more efficient way to code your
function in R. To fix the code you posted, you need to add
brackets around the loop, test x[i] instead of i (which is
always >= 1), and get the length of the loop from x not
pah1\$P. Without the brackets only the first if() is included
in the for loop:

T <- function(x) {
for (i in 1:length(x)) {
if (x[i] >= 1)
print("Combustion")
if (x[i] < 1)
print("Petroleum")
}
}

-------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77840-4352

-----Original Message-----
From: r-help-bounces at r-project.org
[mailto:r-help-bounces at r-project.org] On Behalf Of Rui
Sent: Monday, July 29, 2013 3:46 AM
Cc: r-help at r-project.org
Subject: Re: [R] R function

Hello,

Sorry, that should be

T <- function(x){
ifelse(x > = 1, "Combustion", "Petroleum")
}

Em 29-07-2013 09:32, Rui Barradas escreveu:
> Hello,
>
> Try the following.
>
> T <- function(x){
>      ifelse(pah1\$P > = 1, "Combustion", "Petroleum")
> }
>
> T(pah1\$P[1:83])
>
>
> Hope this helps,
>
>
> Em 29-07-2013 06:35, javad bayat escreveu:
>> Dear R users;
>> I am MSc student and I want to write my own function, but
it cant be
>> completed. please help me for solve it. here is my code:
>>
>> pah1\$P = (pah1\$Fluoranthene/pah1\$Pyrene)
>> T = function(x){
>> for (i in 1:length(pah1\$P))
>> if (i >= 1)
>> print("Combustion")
>> if (i < 1)
>> print("Petroleum")
>> }
>> T(pah1\$P[c(1:83),])
>>
>> I wish that R gives me a column that if value greater or
equal to one
>> give
>> "Combustion"  and if value is less than one give
"Petroleum".
>> but my function dose not work.
>> thank you so much for your help.
>>
>>     [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained,
reproducible code.
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible
code.

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help