I have a list of variables named as av1 av2 av3…av144 in my data frame (dat). I want to recode these into another series of variables say main1 main2 main3… main144 as such:
dat$main1<-ifelse (dat$av1==5 or dat2$av1==8 or dat$av1==6,10,0)
dat$main2<-ifelse (dat$av2==5 or dat2$av2==8 or dat$av2==6,10,0)
#…
dat$main144<-ifelse (dat1$av144==5 or dat$av144==8 or dat$av144==6,10,0)
Could anyone please tell me how can I apply this ifelse command over two sets of variables without re-writing the same line 144 times? I have unsuccessfully experimented with "grep" trying to extract by column names but I think I was in the wrong direction…
Thank you very much in advance,
Now lightly tested:
dat[gsub("av", "main", names(dat))] <-
lapply(dat[grep("av", names(dat))],
function(col) { ifelse (col==5 | col==8 | col==6, 10, 0) } )
SimonO101 provided a dataset that was less complex than I was expecting was being discussed. Here is a slightly more complex but still reasonably minimal test of my code (now that I fixed the missing comma that was in the first version) AND (fixed the logical error in assigning rows to columns):
dat <- data.frame( one=1, two=2, av1 = sample(8) , av2 = sample(8) , av3 = sample(8) );
dat <- cbind(dat, sapply(dat[grep("av", names(dat))],
function(col) { ifelse (col==5 | col==8 | col==6, 10, 0) } ) )
dat
#----------------
one two av1 av2 av3 av1 av2 av3
1 1 2 4 3 4 0 0 0
2 1 2 6 2 5 10 0 10
3 1 2 7 7 8 0 0 10
4 1 2 5 8 1 10 10 0
5 1 2 2 5 6 0 10 10
6 1 2 1 1 7 0 0 0
7 1 2 3 4 3 0 0 0
8 1 2 8 6 2 10 10 0
#--------------
names( dat)[6:8] <- gsub("av", "main", names(dat)[6:8])
dat
#-----------------
one two av1 av2 av3 main1 main2 main3
1 1 2 4 3 4 0 0 0
2 1 2 6 2 5 10 0 10
3 1 2 7 7 8 0 0 10
4 1 2 5 8 1 10 10 0
5 1 2 2 5 6 0 10 10
6 1 2 1 1 7 0 0 0
7 1 2 3 4 3 0 0 0
8 1 2 8 6 2 10 10 0
Here's a similar approach, with some reproducible data for illustrative purposes. I find the locations in dat that meet the condition and change those values in a results df to 10.
set.seed(1)
dat <- data.frame( av1 = sample(8) , av2 = sample(8) , av3 = sample(8) )
# av1 av2 av3
#1 3 6 6
#2 8 1 7
#3 4 2 3
#4 5 7 4
#5 1 3 5
#6 7 8 1
#7 2 4 2
#8 6 5 8
# Initialise a df to hold results, fill with FALSE values (0)
out <- `[<-`(dat , , , 0 )
# Find where values should be TRUE
ind <- sapply( dat , function(x) x %in% c( 5 , 6 , 8 ) )
# Change to 10
out[ ind ] <- 10
# Change names if desired
names(out) <- gsub( "av" , "main" , names(dat) )
# main1 main2 main3
#1 0 10 10
#2 10 0 0
#3 0 0 0
#4 10 0 0
#5 0 0 10
#6 0 10 0
#7 0 0 0
#8 10 10 10
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.