How to use "if" within "apply"

I am a very bigger of R. I do appreciate your help.

I have a set of responses to four questions from students (A~D). The data format is like below.

  A B C D
1 1 0 1 0
2 0 1 1 0
3 1 0 1 1
4 0 1 0 1

If an answer from students is "1", the number should be replaced in "Yes."
If an answer from students is "0", the number should be replaced in "No."

This is the simplification what I want to do.

With the limited knowledge, I wrote the code using "apply"

res <- apply(data, 2, function(x){
	if (x == 1){
		"Yes"
		}
	else{
		"No"
		}
	}
)

However, I received warning messages:

1: In if (x == 1) { :
  the condition has length > 1 and only the first element will be used

And I got the first element of each column as the result.

    A     B     C     D 
"Yes"  "No" "Yes"  "No" 

I am sure that I need to more explore the documents and web recourses, but your kind help would be much appreciated. Thank you very much.

look into the ifelse() function, which is a vectorised form of applying a conditional logic on each entry of a vector

1 Like

Thank you. I modified the code and got the data in a way I wanted!

res <- ifelse(data == 1, "Yes", "No")

> res
     A     B     C     D    
[1,] "Yes" "No"  "Yes" "No" 
[2,] "No"  "Yes" "Yes" "No" 
[3,] "Yes" "No"  "Yes" "Yes"
[4,] "No"  "Yes" "No"  "Yes"

Thank you!!!!!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.