purpleblau
purpleblau

Reputation: 589

R How to replace string with Variables?

I have a simple question that I can't seem to find the question.

Color<-'Blue'
Transparency<-'Clear'

Data<-subset(Data,Data$AAA== Color  & Data$BBB== Transparency)

I want to assign the strings to a variable so it's reusable for better readability and code re-usability.

I tried with eval() and get(), too bad, it doesn't really work. Thank you!

Upvotes: 0

Views: 142

Answers (2)

jlhoward
jlhoward

Reputation: 59425

This should work.

Data<-subset(Data,AAA== Color  & BBB== Transparency)

Example:

df <- data.frame(AAA=c("red","green","blue"),BBB=c("clear","cloudy","opaque"))
color<-"red"
trans<-"clear"

subset(df,AAA==color&BBB==trans)
#   AAA   BBB
# 1 red clear

Upvotes: 1

Davide Passaretti
Davide Passaretti

Reputation: 2761

This may help (see if it works):

Color <- c("yellow", "green", "blue")
Transparency <- c("A", "B", "C")

Data <- list(3)

for(i in 1:3) {
     Data[[i]] <- subset(Data, Data$AAA== Color[i]  & Data$BBB== Transparency[i])
}

Upvotes: 1

Related Questions