Angela Ju
Angela Ju

Reputation: 37

How to refer a variable based on substring match result

I wanted to add value label to a variable in the data frame. However, the variable name is based on substring match result. For example, I tried to look for a variable whose name include string “Gender", so I used the code

mn<-grep("Gender",names(data),value=TRUE)

to locate the variable.

Then I wanted to add value label for that variable, I tried:

data$mn<-factor(data$mn,levels=c(2,3),labels=c("Male","Female"))

but it did not work. Could anybody help me to fix the problem? Many thanks

Upvotes: 1

Views: 64

Answers (1)

akrun
akrun

Reputation: 887118

If there are multiple variables that match with 'Gender' in the names, we can loop it with lapply.

 data[,mn] <- lapply(data[,mn], function(x)
             factor(x, levels=2:3, labels=c('Male', 'Female'))

If the 'mn' has a length of 1 i.e. only a single column is matched, we don't need a loop (as showed in the comments by @Angela Ju)

 data[,mn] <- factor(data[,mn],levels=c(2,3),labels=c("Male","Female"))

Upvotes: 1

Related Questions