[R] paste first row string onto every string in column

Benilton Carvalho bcarvalh at jhsph.edu
Wed Aug 12 16:31:22 CEST 2009


you could stick everything in a 1-liner, but that would make it less  
readable:

myf <- function(x){
   tmp <- as.character(x)
   c(tmp[1], paste(tmp[1], tmp[-1], sep=""))
}
df2 <- as.data.frame(sapply(df, myf))


b


On Aug 12, 2009, at 3:39 AM, milton ruser wrote:

> Hi Jill,
>
> Completely not elegant, but may be usefull.
> Of course other colleagues will solve this with 1 line command :-)
>
> cheers
>
> milton
>
>
> df<-read.table(stdin(), head=T, sep=",")
> V1,V2,V3,V4
> DPA1*,DPA1*,DPB1*,DPB1*
> 0103,0104,0401,0601
> 0103,0103,0301,0402
>
> df.new<-as.matrix(df)
> for (i in 2:dim(df)[1])
> {
> for (j in 1:dim(df)[2])
>  {
>  df.new[i,j]<-paste(c(as.character(df[1,j])),  
> c(as.character(df[i,j])),
> sep="")
>  }
> }
> df.new<-data.frame(df.new)
> df
> df.new
>
>
>
> On Tue, Aug 11, 2009 at 9:48 PM, Jill Hollenbach <jhollenbach at chori.org 
> >wrote:
>
>>
>> Hi,
>> I am trying to edit a data frame such that the string in the first  
>> line is
>> appended onto the beginning of each element in the subsequent rows.  
>> The
>> data
>> looks like this:
>>
>>> df
>>     V1   V2   V3   V4
>> 1   DPA1* DPA1* DPB1* DPB1*
>> 2   0103 0104 0401 0601
>> 3   0103 0103 0301 0402
>> .
>> .
>> and what I want is this:
>>
>>> dfnew
>>     V1   V2   V3   V4
>> 1   DPA1* DPA1* DPB1* DPB1*
>> 2   DPA1*0103 DPA1*0104 DPB1*0401 DPB1*0601
>> 3   DPA1*0103 DPA1*0103 DPB1*0301 DPB1*0402
>>
>> any help is much appreciated, I am new to this and struggling.
>> Jill
>>
>> ___
>> Jill Hollenbach, PhD, MPH
>>   Assistant Staff Scientist
>>   Center for Genetics
>>   Children's Hospital Oakland Research Institute
>>   jhollenbach at chori.org
>>
>> --
>> View this message in context:
>> http://www.nabble.com/paste-first-row-string-onto-every-string-in-column-tp24928720p24928720.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<http://www.r-project.org/posting-guide.html 
>> >
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.



More information about the R-help mailing list