Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this dataframe with a column a. I would like to add a different column 'b' based on column 'a'.

For: if a>=10, b='double'. Otherwise b='single'.

How can I do it?

Sample output:

a b
2 single
2 single
4 single
11 double
12 double
12 double
45 double
4 single
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
217 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use ifelse to act on vectors with if statements.

ifelse(a>=10, "double", "single")

So your code could look like this

mydata <- cbind(a, ifelse(a>10, "double", "single"))

(Specified in comments below that if a=10, then "double")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...