I have a column of numbers from 1:1000. I want to append the label "s" to the front of each number so that the total number of characters in each cell remains the same. For instance, "1" would become "s0001", "15" would become "s0015", "620" would become "s0620", and "1000" would become "s1000".
我曾尝试使用封套的<代码>,如果是,那么我就会发现该条件已经过长的错误;只有第一点内容才能使用。
这里是一套实例数据,使用Im代码:
df=data.frame(code=seq(1:1000))
df$code=
if (df$code < 10) { df$code=paste("s000",df$code,sep="") } else
if (100 > df$code & df$code >= 10) { df$code=paste("s00",df$code,sep=="") } else
if (1000 > df$code & df$code >= 100) { df$code=paste("s0",df$code,sep="") } else
{ df$code=paste("s",df$code,sep="") }
I suspect there is an easier way to do this without using if else
. Any thoughts?
感谢!
<>Solution
感谢约兰! 如果X是非连续的惯性:
d=data.frame(x=sample(1:1000,500))
d$nc=nchar(d$x)
ddply(d,.(nc),transform,lab = paste("s",paste(rep("0",4-unique(nc)),collapse = ""),x,sep = ""))