0

I want to make every element in the dataframe (except fot the ID column) become a 0 if it is any number other than 1.

I have:

ID  A B C D E
abc 5 3 1 4 1
def 4 1 3 2 5

I want:

ID  A B C D E
abc 0 0 1 0 1
def 0 1 0 0 0

I am having trouble figuring out how to specify for this to be done to do to every entry in every column and row.

Here is my code:

apply(dat.lec, 2 , function(y) 
  if(!is.na(y)){
      if(y==1){y <- 1}
      else{y <-0} 
     }
  else {y<- NA}
)

Thank you for your help!

2
  • 1
    Have you tried using apply over columns and rows by setting MARGIN = c(1,2)? You could do that for dat.lec[ ,-1] to exclude the ID column. Commented Nov 16, 2017 at 21:56
  • This took care of t! Thank you very much!!! Commented Nov 16, 2017 at 22:01

1 Answer 1

2

No need for implicit or explicit looping.

# Sample data
set.seed(2016);
df <- as.data.frame(matrix(sample(10, replace = TRUE), nrow = 2));
df <- cbind.data.frame(id = sample(letters, 2), df);
df;
#  id V1 V2 V3 V4 V5
#1  k  2  9  5  7  1
#2  g  2  2  2  9  1    

# Replace all entries != 1 with 0's
df[, -1][df[, -1] != 1] <- 0;
df;
#  id V1 V2 V3 V4 V5
#1  k  0  0  0  0  1
#2  g  0  0  0  0  1
Sign up to request clarification or add additional context in comments.

2 Comments

This works great but it also gets rid of all my Id's in column 1, how can I have the first column remain the same?
@KatyTorres Please see my updated answer. If you have additional ID columns, just exclude them when replacing entries.

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.