将列与因子组合(级别:0 =否; 1 =同意)

时间:2013-08-03 16:21:17

标签: r

我有一个愚蠢的问题要问。我试图将两个列与因子结合起来,使其成为一个列。

级别(0和1)与no和yes相同。

所以,如果我将1和1结合起来,它应该给我1; 0和1为1等...

感谢您提供任何信息...... 穆拉利

> sessionInfo()
R version 2.15.1 (2012-06-22)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

> head(testmerge$glucosystemic,10)
 [1] 0 0 0 0 0 0 0 0 0 0
Levels: 0 1 glucosystemic
> head(testmerge$glucolocal,10)
 [1] 0 0 0 0 0 1 1 0 0 1
Levels: 0 1 glucolocal
> str(testmerge$glucosystemic)
 Factor w/ 3 levels "0","1","glucosystemic": 1 1 1 1 1 1 1 1 1 1 ...
> str(testmerge$glucolocal)
 Factor w/ 3 levels "0","1","glucolocal": 1 1 1 1 1 2 2 1 1 2 ...

这解决了问题

### from stackflow help
glucomerge <- function(vec1, vec2) {as.numeric(as.numeric(vec1) + as.numeric(vec2) > 2)}
testmerge$glucoco <- glucomerge(testmerge$glucosystemic,testmerge$glucolocal)

谢谢

3 个答案:

答案 0 :(得分:1)

只需使用以下内容:

as.numeric(as.numeric(vec1) + as.numeric(vec2) > 2)

你可以将它包装在一个很好的函数中,只需运行:

 FactorOR(testmerge[, c("glucosystemic", "glucolocal")])
 #  [1] 0 0 0 0 0 1 1 0 0 1


# Where the function is defined as: 
FactorOR <- function(TwoColDF) {
    as.numeric(as.numeric(TwoColDF[,1]) + as.numeric(TwoColDF[,2]) > 2)
} 

答案 1 :(得分:1)

或:

x3 <- ifelse(x1 == 1 | x2 == 1, 1, 0)

答案 2 :(得分:0)

假设您的数据是testmerge,您可以使用interaction

testmerge$col<-with(testmerge, interaction (glucosystemic,glucolocal))

更新:您可以使用as.numeric分配级别。

testmerge$col<-with(testmerge, as.numeric(interaction (glucosystemic,glucolocal)))