danobolg321
2010-Nov-24 23:06 UTC
[R] Create new string of same length as entry in dataframe
I suspect that this is simple, but thanks in advance for any advice... I have a dataframe, t2: V1 V2 aaa 3 aaaa 4 aaaaaa 6 a 1 aa 2 V2 is the length of the string in V1 using nchar(as.character(t1$V1)) I'd like to create a third column, that contains a string of the length of V2, but containing an alternate text, e.g. V1 V2 V3 aaa 3 bbb aaaa 4 bbbb aaaaaa 6 bbbbbb a 1 b aa 2 bb or V1 V2 V3 aaa 3 bad aaaa 4 badb aaaaaa 6 badbad a 1 b aa 2 ba Suggestions would be much appreciated! Thanks. -- View this message in context: http://r.789695.n4.nabble.com/Create-new-string-of-same-length-as-entry-in-dataframe-tp3058232p3058232.html Sent from the R help mailing list archive at Nabble.com.
Phil Spector
2010-Nov-24 23:28 UTC
[R] Create new string of same length as entry in dataframe
Suppose you want to replace using all b's:> thestring = 'bbbbbbbbbbbbbbbbbbbbbbbbbb' > t2$V3 = substring(thestring,1,t2$V2) > t2$V3[1] "bbb" "bbbb" "bbbbbb" "b" "bb" For the second case,> thestring = paste(rep('bad',5),collapse='') > thestring[1] "badbadbadbadbad"> t2$V3 = substring(thestring,1,t2$V2) > t2$V3[1] "bad" "badb" "badbad" "b" "ba" Hope this helps. - Phil Spector Statistical Computing Facility Department of Statistics UC Berkeley spector at stat.berkeley.edu On Wed, 24 Nov 2010, danobolg321 wrote:> > I suspect that this is simple, but thanks in advance for any advice... > > I have a dataframe, t2: > > V1 V2 > aaa 3 > aaaa 4 > aaaaaa 6 > a 1 > aa 2 > > > V2 is the length of the string in V1 using nchar(as.character(t1$V1)) > > I'd like to create a third column, that contains a string of the length of > V2, but containing an alternate text, e.g. > > V1 V2 V3 > aaa 3 bbb > aaaa 4 bbbb > aaaaaa 6 bbbbbb > a 1 b > aa 2 bb > > or > > V1 V2 V3 > aaa 3 bad > aaaa 4 badb > aaaaaa 6 badbad > a 1 b > aa 2 ba > > > Suggestions would be much appreciated! > > Thanks. > > > -- > View this message in context: http://r.789695.n4.nabble.com/Create-new-string-of-same-length-as-entry-in-dataframe-tp3058232p3058232.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >
danobolg321
2010-Nov-24 23:51 UTC
[R] Create new string of same length as entry in dataframe
Simple, but was taking me a long time to google. Thanks Phil, happy Thanksgiving. -- View this message in context: http://r.789695.n4.nabble.com/Create-new-string-of-same-length-as-entry-in-dataframe-tp3058232p3058275.html Sent from the R help mailing list archive at Nabble.com.