Julie Sletten Julie Sletten - 2 months ago 6
R Question

Merge two rows in a data frame

I have a data frame that looks something like this:

V2 V3 V4
Case 1 1 2
Reg "A" "B" "D"
H 11 16 12
M 14 15 13
S 13 56 34


I would like to combine the two rows called "Case" and "Reg" into one row called "ID". I would like it to look like this:

V2 V3 V4
ID "1A" "1B" "2D"
H 11 16 12
M 14 15 13
S 13 56 34


I would be very grateful if someone has a simple solution to this!

Answer

Here is an idea with a lot of pasting, i.e.

unname(sapply(df, function(i) 
                 paste(paste(i[1:2], collapse = ''), '=', paste(i[3:5], collapse = ':'))))

#[1] "1A = 11:14:13" "1B = 16:15:56" "2D = 12:13:34"

EDIT

Based on your updated question we can do the following,

df1 <- rbind(paste0(df['Case',], df['Reg',]), df[3:nrow(df),])
rownames(df1)[1] <- 'ID'
df1
#   V2 V3 V4
#ID 1A 1B 2D
#H  11 16 12
#M  14 15 13
#S  13 56 34
Comments