Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

Program a sequence of words in a Vector using R

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...