简体   繁体   中英

In R: Extract partial rows (within a subset of columns) in dataframe and stack into new longer dataframe

I have a wide dataframe where each subset of columns relates to a brand, per survey participant. This needs to be restacked so that each brand has its own row. Of course this means instead of 1 row per participant there will be multiple rows. The brand indicator is the number at the end of each column/variable name. I tried to demonstrate below, but this code generates errors.

 #Generate dataframe in wide format
    ID<-c(1,2,3,4)
    Q14_1_PREFERREDstore<-c("PREFERRED store","NA","PREFERRED store","PREFERRED store")
    Q14_2_Widerange<-c("Wide range","NA","Wide range","NA")
    Q14_1_PREFERREDstore__1<-c("PREFERRED store","NA","NA","PREFERRED store")
    Q14_2_Widerange__1<-c("NA","NA","Wide range"," Wide range ")
    Q14_1_PREFERREDstore__2<-c("PREFERRED store","NA","PREFERRED store","PREFERRED store")
    Q14_2_Widerange__2<-c("Wide range"," Wide range ","Wide range","NA")

df<-data.frame(ID,Q14_1_PREFERREDstore,Q14_2_Widerange,Q14_1_PREFERREDstore__1,Q14_2_Widerange__1,Q14_1_PREFERREDstore__2,Q14_2_Widerange__2)


#Stack into new semi-wide dataframe
df2<-NULL

ID2<-c(1,1,1,2,2,2,3,3,3,4,4,4)

df2$ID2<-data.frame(ID2)

df2$brand[1,2:3]<-df[1,2:3]
df2$brand1[2,2:3]<-df[1,4:5]
df2$brand2[3,2:3]<-df[1,6:7]
df$brand3[4,2:3]<-df[1,8:9]

You could coerce the rows to matrix es with ncol=2 columns using lapply and rbind them.

First you could clean your data with trimws since there appear to be some white spaces as "Wide range " (try with or without this line).

df[] <- lapply(df, trimws)

res <- do.call(rbind, lapply(1:nrow(df), function(x) 
  data.frame(id=x, matrix(df[x, -1], ncol=2, byrow=TRUE))))
res
#    id              X1         X2
# 1   1 PREFERRED store Wide range
# 2   1 PREFERRED store         NA
# 3   1 PREFERRED store Wide range
# 4   2              NA         NA
# 5   2              NA         NA
# 6   2              NA Wide range
# 7   3 PREFERRED store Wide range
# 8   3              NA Wide range
# 9   3 PREFERRED store Wide range
# 10  4 PREFERRED store         NA
# 11  4 PREFERRED store Wide range
# 12  4 PREFERRED store         NA

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