[R] merge some columns
Dennis Murphy
djmuser at gmail.com
Fri Sep 2 15:15:12 CEST 2011
Hi:
Here's one approach:
d <- read.table(textConnection("
V1 V2 V3 V4 V5 V6
1 G A G G G G
2 A A G A A G"), header = TRUE, stringsAsFactors = FALSE)
closeAllConnections()
# Create two vectors of variable names, one for odd numbered,
# one for even numbered
vars1 <- names(d)[seq_along(names(d)) %% 2 == 1]
vars2 <- names(d)[seq_along(names(d)) %% 2 == 0]
# Apply the paste sequentially to corresponding pairs
# in vars1 and vars2; get() is used to get the data associated
# with the variable names in vars1 and vars2
d2 <- sapply(seq_along(vars1),
function(j) with(d, paste(get(vars1[j]), get(vars2[j]), sep = '/')))
# Convert to data frame:
d2 <- as.data.frame(d2, stringsAsFactors = FALSE)
str(d2)
HTH,
Dennis
On Fri, Sep 2, 2011 at 5:34 AM, Joao Fadista <Joao.Fadista at med.lu.se> wrote:
> Dear all,
>
> I would like to know how to merge columns like:
>
> Input file:
> V1 V2 V3 V4 V5 V6
> 1 G A G G G G
> 2 A A G A A G
>
> Desired output file:
> V1 V2 V3
> 1 G/A G/G G/G
> 2 A/A G/A A/G
>
> So for every 2 consecutive columns merge their content into one.
> Thanks in advance.
>
>
> [[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