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

How can you create a vector in R which consists of a sequence of different words?

Something like Vec_Sex: for 0 to 6, input "Male" and for 7 to 9, input "Female"...

I know shortcuts like rep(1:3,times=4) etc... But even after flicking through my lecture notes and a goole search, I'm unsure how to achieve this with words and when the amount of elements that contain that word differ...

Outcome would be something like:

Vec_Sex = [ Male, Male, Male, Male, Male, Male, Male, Female, Female, Female ]

Thanks.

See Question&Answers more detail:os

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

1 Answer

Just use rep and c. Examples:

c(rep("Male", 7), rep("Female", 3))
# [1] "Male"   "Male"   "Male"   "Male"   "Male"   "Male"   "Male"   "Female" "Female" "Female"
rep(c("Male", "Female"), times = c(7, 3))
# [1] "Male"   "Male"   "Male"   "Male"   "Male"   "Male"   "Male"   "Female" "Female" "Female"

Note that times can be a vector specifying how many times to repeat each element.

Also, note that R starts indexing at 1, not zero.


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

548k questions

547k answers

4 comments

86.3k users

...