Reputation: 3
I have a beginner R question.
I want to add a column "d" that has a value of 1 if the corresponding row in "c" is >4, and 0 otherwise. I think that if I can do this basic thing I can extend the logic to my other questions. Basically, I can't figure out how to do basic comparisons between entries in a given row.
Here is a sample set of code:
# initial data
a=c(0,1,1)
b=c(1,2,3)
c=c(4,5,6)
data=data.frame(a,b,c)
Any help would be appreciated. Thanks!
Upvotes: 0
Views: 274
Reputation: 94202
One way:
> data
a b c
1 0 1 4
2 1 2 5
3 1 3 6
> data$d=ifelse(data$c>4,1,0)
> data
a b c d
1 0 1 4 0
2 1 2 5 1
3 1 3 6 1
Another common way is to rely on the fact that TRUE/FALSE convert to 1/0 when converted to numeric:
> data$d2=as.numeric(data$c>4)
> data
a b c d d2
1 0 1 4 0 0
2 1 2 5 1 1
3 1 3 6 1 1
Upvotes: 1