简体   繁体   中英

How do I recode character variable?

I am a beginner in R so this is a very basic question. I do not find a specific answer to it so I would like to ask you here.

I'm confronted with the following challenge; I'd like to recode a character variable and create one out of this.

Specifically, the variable in my data frame(data) is called "driver", with the categories "market", "legislation", "technology", and "mixed".

Now I would simply like to create a new variable, "driverrec", with the values "market" and "others". In "others" the three remaining variables shall be summarized.

I tried it with this page: http://rprogramming.net/recode-data-in-r/

Basically, I tried the following code to adopt on mine, but it won't work for more than one category.

#Create a new field called NewGrade
SchoolData$NewGrade <- recode(SchoolData$Grade,"5='Elementary'")

# my attempt
driverrec <- data$driver
recode(driverrec, "'Mixed'='others'") This is working.

But the whole recode is not working:

recode(driverrec, "'Mixed'='others'", "'Technology'='others'", 
"'Legislation'='others'", "'Market'='market'" ) 

I am looking forward to and thank you for your help.

I found a solution not using the replace command:

data$driverrec[dataframe$driver=='Market'] <- 'market' data$driverrec[is.na(dataframe$driver)==TRUE] <- 'others'

This worked fine; in order, someone is looking for a solution ;)!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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