iGada
iGada

Reputation: 633

How to append the column in R?

Consider the following data named mydata. My intention is to put v1 and v2 in the same column by adding an identifier variable v4.

id v1 v2 
1  2  3
2  4  5
3  7  8

OUTPUT required:

id v3 v4 
1  2  1
2  4  1
3  7  1
1  3  2
2  5  2
3  8  2

Any help is much appreciated!

Upvotes: 0

Views: 55

Answers (3)

SEAnalyst
SEAnalyst

Reputation: 1211

I think you are looking for something like dplyr::mutate() for adding columns, and rbind() for stacking two data frames on top of each other.

library(dplyr)    
mydata <- data.frame (id  = c(1,2,3),
                      v1 = c(2,4,7),
                      v2 = c(3,5,8))
)

a<- data.frame(mydata$id, mydata$v1)%>%
  mutate(v4=1)%>%
  rename(v3=mydata.v1, id=mydata.id )

b<- data.frame(mydata$id, mydata$v2)%>%
  mutate(v4=2)%>%
      rename(v3=mydata.v2, id=mydata.id )
    
> rbind(a,b)
  id v3 v4
1  1  2  1
2  2  4  1
3  3  7  1
4  1  3  2
5  2  5  2
6  3  8  2

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

A data.table option

setcolorder(
  transform(
    setnames(melt(setDT(df), id.var = "id", variable.name = "v4"), "value", "v3"),
    v4 = as.numeric(factor(v4))
  ), c("id", "v3", "v4")
)[]

gives

   id v3 v4
1:  1  2  1
2:  2  4  1
3:  3  7  1
4:  1  3  2
5:  2  5  2
6:  3  8  2

Upvotes: 1

Bram
Bram

Reputation: 342

What about this:

mydata <- data.frame(c(1,2,3),c(2,4,7),c(3,5,8))
colnames(mydata) <- c("id","v1","v2")



mydata_2 <- rbind(mydata[,c(1,2)], setNames(mydata[,c(1,3)], names(mydata[,c(1,2)])))
mydata_2$v4 <- c(rep(1,length(mydata$v1)),rep(2,length(mydata$v2)))
colnames(mydata_2) <- c("id","v3","v4")

Upvotes: 1

Related Questions