Reputation: 1339
I would like to write a loop which will help me to create a vector with strings. I have table with strings and number how many times each string should be repeated.
Rival Elements
1 ORL 3
2 MIA 4
So my code should create a vector, v = ORL, ORL, ORL, MIA, MIA, MIA, MIA
i <- 1
while (i <= 1) {
xx <- c(rep(qwe$Rival[i], qwe$Elements[i]))
i<- i+1
print(xx)
}
and instead of these xx = ORL, ORL, ORL, I received xx = 23,23,23. How to get string instead of these number?
Upvotes: 0
Views: 107
Reputation: 3223
Column "Rival" in your dataframe is obviously defined as factor. applying function c() to a factor, results in the numeric representation of the factor levels, see:
c(qwe$Rival)
in this case use as.vector() instead. However, like Pascal commented the c()-function is unnecessary in your code.
To get rid of the loop, you get your vectors by using
xx = mapply(rep, qwe$Rival, qwe$Elements)
Upvotes: 0
Reputation: 10233
Is this what you want?
# Load your data
qwe <- read.table(stringsAsFactors = FALSE, text = "
Rival Elements
1 ORL 3
2 MIA 4 ")
#qwe$Rival <- as.character(qwe$Rival) # May or may not be needed
v <- with(qwe, rep(Rival, Elements))
print(v)
#[1] "ORL" "ORL" "ORL" "MIA" "MIA" "MIA" "MIA"
Make sure that qwe$Rival
is a character
.
Or do you want the following?
u <- paste(v, collapse = ", ")
print(u)
#[1] "ORL, ORL, ORL, MIA, MIA, MIA, MIA"
Which is a vector of length one with the element shown.
Upvotes: 1
Reputation: 309
At a first look your problem could be solved by using as.character().
Also you want <= 2 as R starts counting at 1, not 0.
Upvotes: 0