我有这样的数据框:
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
...
谢谢。
答案 0 :(得分: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
答案 1 :(得分: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