How to create a column containing a string of stars to inidcate levels of a factor in a data frame i
Posted
by PaulHurleyuk
on Stack Overflow
See other posts from Stack Overflow
or by PaulHurleyuk
Published on 2010-04-06T14:29:49Z
Indexed on
2010/04/06
14:33 UTC
Read the original article
Hit count: 402
(second question today - must be a bad day)
I have a dataframe with various columns, inculding a concentration column (numeric), a flag highlighting invalid results (boolean) and a description of the problem (character)
dput(df)
structure(list(x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), rawconc = c(77.4,
52.6, 86.5, 44.5, 167, 16.2, 59.3, 123, 1.95, 181), reason = structure(c(NA,
NA, 2L, NA, NA, NA, 2L, 1L, NA, NA), .Label = c("Fails Acceptance Criteria",
"Poor Injection"), class = "factor"), flag = c("False", "False",
"True", "False", "False", "False", "True", "True", "False", "False"
)), .Names = c("x", "rawconc", "reason", "flag"), row.names = c(NA,
-10L), class = "data.frame")
I can create a column with the numeric level of the reason column
df$level<-as.numeric(df$reason)
df
x rawconc reason flag level
1 1 77.40 <NA> False NA
2 2 52.60 <NA> False NA
3 3 86.50 Poor Injection True 2
4 4 44.50 <NA> False NA
5 5 167.00 <NA> False NA
6 6 16.20 <NA> False NA
7 7 59.30 Poor Injection True 2
8 8 123.00 Fails Acceptance Criteria True 1
9 9 1.95 <NA> False NA
10 10 181.00 <NA> False NA
and here's what I want to do to create a column with 'level' many stars, but it fails
df$stars<-paste(rep("*",df$level)sep="",collapse="")
Error: unexpected symbol in "df$stars<-paste(rep("*",df$level)sep"
df$stars<-paste(rep("*",df$level),sep="",collapse="")
Error in rep("*", df$level) : invalid 'times' argument
rep("*",df$level)
Error in rep("*", df$level) : invalid 'times' argument
df$stars<-paste(rep("*",pmax(df$level,0,na.rm=TRUE)),sep="",collapse="")
Error in rep("*", pmax(df$level, 0, na.rm = TRUE)) :
invalid 'times' argument
It seems that rep needs to be fed one value at a time. I feel that this should be possible (and my gut says 'use lapply' but my apply fu is v. poor)
ANy one want to try ?
© Stack Overflow or respective owner