4

我有这样一个数据框:

    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
...

我想将其转换如下,我认为 reshape 在这里没有用,最好的方法是什么?

    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
...

谢谢你。

4

2 回答 2

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
于 2013-03-27T07:24:17.990 回答
2

这是一种半灵活的方式来做你想做的事情。如果你的列号超过 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
于 2013-03-27T10:27:03.337 回答