Lance Bautista
Lance Bautista

Reputation: 11

How to pass a Concatenate Strings to a Function in R

I am having a problem of how to pass a concatenated strings that is similar to the name of the datasets in my global data. Name1 to Name12 is a dataset

Name1 3obs of 2variables

Name2 4obs of 2variables

...

Name12 2obs of 2variables

I want to simplify my code since so I made a for loop to print each dataset name

for(j in 1:12){
name<-paste("Name",j,sep="")
print(name)
}

after that I tried passing it to the function

for(j in 1:12){
name<-paste("Name",j,sep="")
Greetings(name)
}

but i encounter

Error in name$gender : $ operator is invalid for atomic vectors

Greetings <- function(name){
check<-name$gender
if(check==male) cat("Greetings","Mr",name$person)
else cat("Greetings","Ms",name$person)
}

Upvotes: 1

Views: 1388

Answers (2)

Cinnamon Star
Cinnamon Star

Reputation: 24

You do not have a problem with the String, it's totally fine. Rather you need a database for checking the gender. You cannot just call $gender on a string, hoping it will tell you if it's male or female. You will need a data.frame or a table where you can look up if the name is female or male.

Additionally, also name$person won't work, as name is only a String. Do not mix strings and data.frame/table.

If you already have a data.frame/table where the gender is deposited, you have to extract this value from the data.frame/table with dataFrame[name=name,]$gender respectively dataFrame[name=name,]$person where the first name is the column caption and the second name your variable, containing the name you want to examine as String.

EDIT: You need to use eval(as.name(name)) to reference the variable, if name is a String containing the name of the variable.

Upvotes: 1

SymbolixAU
SymbolixAU

Reputation: 26258

Inside your Greetings function, name is a string, not a data.frame. Put a print(name) inside your Greetings function to see this.

Greetings <- function(name){
  print(name)
  # check<-name$gender
  # if(check==male) cat("Greetings","Mr",name$person)
  # else cat("Greetings","Ms",name$person)
}
Greetings(name)
# [1] "Name1"

See that this is just a string, not your data.frame

To use the string name to refer to your data.frame, you need to use get() to refer to your R object.

Consider this example data:

Name1 <- data.frame(gender= c("male"),
                    person= c("a"), stringsAsFactors = FALSE)

## Create a string representing the data.frame as per your original code 
## (can be done in a loop)
name <- paste("Name", "1", sep="")

In the Greetings function, you can refer to the data.frame with get(name). (you also need quotes around male), something like

Greetings <- function(name){
  check <- get(name)

  ## note this will only work as expected with a data.frame 
  ## with one row.
  if(check$gender=="male") cat("Greetings","Mr", check$person)
  else cat("Greetings","Ms",check$person)
}

Greetings(name)
# Greetings Mr a

Upvotes: 1

Related Questions