Venkatesh
Venkatesh

Reputation: 45

Merge 10 variables in pairs and make them into one variable

This is how my files looks like :

#Var1    Var2   Var3  Var4
#0         1    2       1

I want something like this :

#Var1     Var2
#01        21

I am sorry for any inconvenience, I tried to be as clear as possible in asking this question. I am very new to R and stackoverflow. I really appreciate any help.

Upvotes: 1

Views: 105

Answers (2)

Arun
Arun

Reputation: 118849

Just another way (assuming tt is your data.frame):

sapply(seq(1, ncol(tt), by=2), function(x) do.call(paste0, c(tt[,x:(x+1)])))
# [1] "01" "21"

(or) as @Sven shows under comment:

setNames(as.data.frame(lapply(seq(1, ncol(tt), by=2), 
         function(x) do.call(paste0, c(tt[,x:(x+1)])))), names(tt)[1:2])

Upvotes: 2

Sven Hohenstein
Sven Hohenstein

Reputation: 81713

# The data
dat <- data.frame(0, 1, 2, 1)

# Transform data
as.data.frame(lapply(c(1, 3), function(x) paste(dat[c(x, x+1)], collapse = "")))

  X.01. X.21.
1    01    21

Upvotes: 1

Related Questions