2

I have a dataframe called reshapedwcw as follows. I want to use the apply function to convert the data to binary data where the value is present reshapewcw

    D009325 D009357 D009369 D009373 D009404 D009437 D009442 D009447  
r1    1       0       0       2       0       0       44      78        
r2    0       3       4       0       2       1       2       2 
r3    1       2       1       2       3       87      99      2  

Desired Output

    D009325 D009357 D009369 D009373 D009404 D009437 D009442 D009447 
r1    1       0       0       1       0       0       1       1               
r2    0       1       1       0       1       1       1       1        
r3    1       1       1       1       1       1       1       1    

In addition, kindly let me what is wrong with this approach and is there a better alternative

indices <- which(apply(reshapedwcw,2,function(x) x>1)) 
reshapedwcw[indices]<-1
4
  • Regarding why apply doesn't work, look at the indices it gives -- they are per-column, not positions in the full table. ycw's answer below shows the correct analog you can use. Commented Apr 11, 2017 at 16:21
  • @KHAN ifan I have updated my answer. My approach is not only valid for vector, but also valid for matrix and data frame. There is no need to use apply function. Commented Apr 12, 2017 at 10:04
  • @ycw what if I want to perform this operation from 3rd column to last column? can you write the syntax ? Commented Apr 12, 2017 at 10:14
  • @KHAN ifan temp_df <- reshapedwcw[, 3:8], temp_df[temp_df > 0] <- 1, reshapedwcw[, 3:8] <- temp_df Commented Apr 12, 2017 at 10:18

3 Answers 3

2
# Create the data frame
m <- matrix(c(1, 0, 0, 2, 0, 0, 44, 78,
              0, 3, 4, 0, 2, 1, 2, 2, 
              1, 2, 1, 2, 3, 87, 99, 2), 
              nrow = 3, byrow = TRUE)

reshapedwcw <- as.data.frame(m)
colnames(reshapedwcw) <- c("D009325", "D009357", "D009369", "D009373", 
                           "D009404", "D009437", "D009442", "D009447")
rownames(reshapedwcw) <- c("r1", "r2", "r3")

# Assign 1 to data larger than 0
reshapedwcw[reshapedwcw > 0] <- 1
Sign up to request clarification or add additional context in comments.

Comments

1

You can convert a binary value to 0/1 values by just adding 0. So you could just do

(reshapewcw>0)+0
#  009325 D009357 D009369 D009373 D009404 D009437 D009442 D009447 D009456 
#       1       0       0       1       0       0       1       1       0 

1 Comment

The reason I wanted to use the apply function is that I have other columns in the data frame that I do not want to disturb. Kindly observe the dataframe
1

You can also do:

as.numeric(reshapewcw>0)

Thanks

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.