basic level R problem - create a function

Bor<-"B"
Berilyum<-"Be"
Hidrojen<-"H"
Helyum<-"He"
Flor <-"F"
Fosfor<-"P"
ls(pattern="^H")
ls(pattern="o")
Fonksiyon1<- function(harf){
  return(ls(pattern=harf ))

Fonksiyon1("H")  
}

Fonksiyon1("H")

character(0)

getting this output. Where is my error?

I think you are coming against an issue related to function environments. ls() lists things in an environment. When run in the console this is your global environment.

However, functions have their own environments. This is why when you write a function with x <- 3 in it, x doesn't appear in your global environment unless you explicitly return() it.

You can tell ls() to use the global environment:

Bor<-"B"
Berilyum<-"Be"
Hidrojen<-"H"
Helyum<-"He"
Flor <-"F"
Fosfor<-"P"

Fonksiyon1 <- function(harf) {
  ls(name = globalenv(), 
     pattern = harf)
}

Fonksiyon1("H")
#> [1] "Helyum"   "Hidrojen"

Created on 2022-10-27 with reprex v2.0.2

2 Likes

#thank you! So what should i do if i want to draw the first letter with "o"?

Fonksiyon2 <- function(^harf) {
ls(name = globalenv(),
pattern = ^harf)
}

Fonksiyon2("^O")

not working

You can't start a function argument with ^ I'm afraid; the below should work:

Fonksiyon1 <- function(harf) {
  ls(name = globalenv(), 
     pattern = harf)
}

Fonksiyon1("^O")
1 Like