Question

I'm trying to recode create new variables based on already existing variables. The following code is what I've come up with. Is there a better way of doing this? For instance do I have to create the separate matrix in advance or can easily create new variables in my already existing dataset?

rec<-c("col1", "col2", "col3", "col4")

recmat<-as.data.frame(matrix(NA,800, length(rec)))
recmat[, 1:length(rec)][0<=dat[,rec] & 1>=dat[,rec]]<-0
recmat[, 1:length(rec)][2<=dat[,rec] & dat[,rec]<=4]<-1

The first lines of dat looks like this:

     col1    col2   col3       col4
1       NA     NA     NA         NA
2       NA     NA     NA         NA
3       NA     NA     NA          1
4        0     NA     NA         NA
5        0     NA     NA         NA
6       NA     NA     NA         NA
7        0      0      0         NA
Was it helpful?

Solution

You can apply a vectorised function to a data frame like so:

f=function(x) ifelse((x>=0 & x<=1),0,ifelse((x>=2 & x<=4),1,NA))
recmat<-f(dat)

or maybe

recmat<-f(dat[,rec])

It would help if you provided an example of what dat might look like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top