как выборочно преобразовать столбцы в строки в data.frame?

у меня есть такой кадр данных:

    a1 a2 a3 a4 b c d1 d2 d3 d4 
[1] 0  0  1  0  0 0 0  1  0  0
[2] 0  1  0  0  1 0 0  1  0  0
...

я хотел бы преобразовать его, как показано ниже, я думаю, что изменение формы здесь не будет полезно, как лучше всего пойти?

    a b c d
[1] 0 0 0 0       # a and d as a1 and d1 of first row
[2] 0 0 0 1       # a and d as a2 and d2 of first row
[3] 1 0 0 0       # a and d as a3 and d3 of first row
[4] 0 0 0 0       # a and d as a4 and d4 of first row
[5] 0 1 0 0       # a and d as a1 and d1 of second row
[6] 1 1 0 1       # a and d as a2 and d2 of second row
[7] 0 1 0 0       # a and d as a3 and d3 of second row
[8] 0 1 0 0       # a and d as a4 and d4 of second row
...

благодарю вас.


person Selin Erguncu    schedule 27.03.2013    source источник


Ответы (2)


Если данные действительно такие простые, подойдет что-то вроде приведенного ниже.

DF <- read.table(text = "a1 a2 a3 a4 b c d1 d2 d3 d4\n0  0  1  0  0 0 0  1  0  0\n0  1  0  0  1 0 0  1  0  0", 
    header = TRUE)
a <- as.vector(t(DF[, c("a1", "a2", "a3", "a4")]))
d <- as.vector(t(DF[, c("d1", "d2", "d3", "d4")]))
b <- rep(DF[, "b"], each = 4)
c <- rep(DF[, "c"], each = 4)
result <- data.frame(a, b, c, d)
result
##   a b c d
## 1 0 0 0 0
## 2 0 0 0 1
## 3 1 0 0 0
## 4 0 0 0 0
## 5 0 1 0 0
## 6 1 1 0 1
## 7 0 1 0 0
## 8 0 1 0 0
person CHP    schedule 27.03.2013
comment
спасибо, хотя данные были не такими простыми, это сработало. - person Selin Erguncu; 27.03.2013

вот полугибкий способ сделать то, что вы пытаетесь сделать.. он сломается, если ваши номера столбцов превысят 9, если вы не используете начальные нули.. и я думаю, что он предполагает, что ваши столбцы отсортированы (что можно сделать с yourdata <- yourdata[ , sort( names( yourdata ) ) ]) и все столбцы идеально делятся на самый длинный столбец (рассчитанный на final.nrow)

x <- read.table(text = "a1 a2 a3 a4 b c d1 d2 d3 d4\n0  0  1  0  0 0 0  1  0  0\n0  1  0  0  1 0 0  1  0  0", 
    header = TRUE)

# this assumes your data are reasonably structured

# here's a way to construct the "a" column in your desired structure--
as.numeric( t( x[ , grepl( "a" , names( x ) ) ] ) )

# so let's find all the column names, without their numbers
cols <- unique( gsub( "[1-9]" , "" , names( x ) ) )

# look at all column headers
cols

# find the number of records in the final table
final.nrow <- nrow( x ) * max( as.numeric( gsub( "[a-z]" , "" , names( x ) ) ) , na.rm = TRUE )

# initiate an empty data frame
y <- NULL

# loop through each of your column names
for ( i in cols ){
    curCol <- as.numeric( t( x[ , grepl( i , names( x ) ) ] ) )

    # find the multiple
    expanded.col <- data.frame( rep( curCol , each = final.nrow / length( curCol ) ) )

    if ( is.null( y ) ) y <- expanded.col else y <- cbind( y , expanded.col )
}

# tack on the final names
names( y ) <- cols

# look at the final result
y
person Anthony Damico    schedule 27.03.2013