R:将数据帧重新整形为1和0的矩阵

时间:2015-07-02 14:51:39

标签: r

我正在尝试转换此类型格式的数据框:

  V1 V2
  1  a
  2  a
  3  b
  4  c
  5  c

进入这种格式的矩阵:

  V1 a  b  c
  1  1  0  0
  2  1  0  0
  3  0  1  0
  4  0  0  1
  5  0  0  1

在R中执行此操作的最佳方法是什么?我曾尝试使用reshape2,但无法想出办法。

6 个答案:

答案 0 :(得分:4)

for ip in ips: try: try: #print curent address print "Connecting to " + ip #Login section c = pexpect.spawn('ssh -o StrictHostKeyChecking=no %s@%s' % (tacacsUser, ip)) c.timeout = 10 c.expect('password:') #Login to the device c.expect('#') except Exception, e: #Write login errors to file print "Login error while connecting to " + ip saveLogs('LoginErrors.txt', e, 'Error connecting to ') #send commands and such except Exception, e: print "Error occured while processing commands for " + ip saveLogs('ConfigErrors.txt', e, 'Error occured while processing ') 应该足够了:

table

或者,您可以查看with(mydf, cbind(V1, table(1:nrow(mydf), V2))) ## V1 a b c ## 1 1 1 0 0 ## 2 2 1 0 0 ## 3 3 0 1 0 ## 4 4 0 0 1 ## 5 5 0 0 1

model.matrix

答案 1 :(得分:4)

也许是捷径,但这与此不一样?

library(reshape2)
dcast(dat, V1 ~ V2, length )
Using V2 as value column: use value.var to override.
  V1 a b c
1  1 1 0 0
2  2 1 0 0
3  3 0 1 0
4  4 0 0 1
5  5 0 0 1

答案 2 :(得分:2)

我不熟悉这方面的特殊功能,但我可能会......

uv <- unique(DF$V2)
m  <- matrix(0L,nrow(DF),length(uv),dimnames=list(DF$V1,uv))
m[ cbind(1:nrow(m), match(DF$V2,uv)) ] <- 1L

这是一个零和一的矩阵,与目前为止的其他答案不同。 (当然,差异很小。)

  a b c
1 1 0 0
2 1 0 0
3 0 1 0
4 0 0 1
5 0 0 1

答案 3 :(得分:2)

另一种选择

library(tidyr)
out = cbind(dat[1], 
      apply(spread(dat, V2, V2)[-1], 2, 
            function(x) ifelse(is.na(x), 0, 1)))

#  V1 a b c
#1  1 1 0 0
#2  2 1 0 0
#3  3 0 1 0
#4  4 0 0 1
#5  5 0 0 1

更简化为@SamFirke建议

library(dplyr)
library(tidyr)
dat %>% mutate(x = 1) %>% spread(V2, x, fill = 0)

#  V1 a b c
#1  1 1 0 0
#2  2 1 0 0
#3  3 0 1 0
#4  4 0 0 1
#5  5 0 0 1

答案 4 :(得分:2)

这是代码高尔夫的答案:

model.matrix(~.-1,df)
##   V1 V2a V2b V2c
## 1  1   1   0   0
## 2  2   1   0   0
## 3  3   0   1   0
## 4  4   0   0   1
## 5  5   0   0   1

答案 5 :(得分:0)

以下是使用 qdapTools 中的mtabulate的方法:

library(qdapTools)
data.frame(dat[, 1, drop=F], mtabulate(setNames(dat[[2]], dat[[1]])))

##   V1 a b c
## 1  1 1 0 0
## 2  2 1 0 0
## 3  3 0 1 0
## 4  4 0 0 1
## 5  5 0 0 1
相关问题