简体   繁体   中英

How do you add additional rows from multiple columns in R?

My DF looks like this:

ID  V1    V2  V3
A   100  200    
B   100     
C   300     
D   400     
E   223  233   4

I want to transform it in R, such that the multiple 'V' columns come under one another with repeating IDs:

ID  V1
A   100
A   200
B   100
C   300
D   400
E   223
E   233
E   4

What is the best way of doing this in R or Excel?

We can use melt

library(data.table)
setnames(melt(setDT(df), id.var="ID", na.rm=TRUE)[order(ID), -2, with = FALSE], 2, "V1")[]
#   ID  V1
#1:  A 100
#2:  A 200
#3:  B 100
#4:  C 300
#5:  D 400
#6:  E 223
#7:  E 233
#8:  E   4

You can also try tidyr:

library(tidyr)
df <- df %>% gather(new, V1, 2:4) %>% filter(!is.na(V1)) 

If you don't want the "new" column add this cody (library "dplyr"):

%>% select(id, V1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM