1

I have the following data frame:

i39<-c(5,3,5,4,4,3)
i38<-c(5,3,5,3,4,1)
i37<-c(5,3,5,3,4,3)
i36<-c(5,4,5,5,4,2)
ndat1<-as.data.frame(cbind(i39,i38,i37,i36))
> ndat1
  i39 i38 i37 i36
1   5   5   5   5
2   3   3   3   4
3   5   5   5   5
4   4   3   3   5
5   4   4   4   4
6   3   1   3   2

My goal is to convert any value that is a 4 or a 5 into a 1, and anything else into a 0 to yield the following:

> ndat1
  i39 i38 i37 i36
1   1   1   1   1
2   0   0   0   1
3   1   1   1   1
4   1   0   0   1
5   1   1   1   1
6   0   0   0   0

2 Answers 2

4

With your data set I would just do

ndat1[] <- +(ndat1 >= 4)
#   i39 i38 i37 i36
# 1   1   1   1   1
# 2   0   0   0   1
# 3   1   1   1   1
# 4   1   0   0   1
# 5   1   1   1   1
# 6   0   0   0   0

Though a more general solution will be

ndat1[] <- +(ndat1 == 4 | ndat1 == 5)
#   i39 i38 i37 i36
# 1   1   1   1   1
# 2   0   0   0   1
# 3   1   1   1   1
# 4   1   0   0   1
# 5   1   1   1   1
# 6   0   0   0   0

Some data.table alternative

library(data.table)
setDT(ndat1)[, names(ndat1) := lapply(.SD, function(x) +(x %in% 4:5))]

And I'll to the dplyr guys have fun with mutate_each

Sign up to request clarification or add additional context in comments.

3 Comments

This method will not work properly, as there may be cases where the data set contains cases that are greater than 4, but less than 5, and I need only cases that exactly 4 or exactly 5.
Definitely a quicker solution thanks! I will up-vote as soon as I can. However, I will say this looks like it is yielding a matrix, and I would prefer a data frame.
I am aware of that, I ran out of up-votes for the day. Also please up-vote my question and answer if you feel it is warranted. Also, thank you for the additional edit, and other option.
0

I used the following to solve this issue:

recode<-function(ndat1){
ifelse((as.data.frame(ndat1)==4|as.data.frame(ndat1)==5),1,0)
}
sum_dc1<-as.data.frame(sapply(as.data.frame(ndat1),recode),drop=FALSE)
> sum_dc1
  i39 i38 i37 i36
1   1   1   1   1
2   0   0   0   1
3   1   1   1   1
4   1   0   0   1
5   1   1   1   1
6   0   0   0   0

I was just wondering if anyone else had any thoughts, but overall I am satisfied with this way of solving the issue. Thank you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.