使用apply函数将数据转换为R中的二进制

时间:2017-04-11 16:11:32

标签: r dataframe apply

我有一个名为reshapedwcw的数据帧,如下所示。我想使用apply函数将数据转换为存在值的二进制数据     reshapewcw

    D009325 D009357 D009369 D009373 D009404 D009437 D009442 D009447  
r1    1       0       0       2       0       0       44      78        
r2    0       3       4       0       2       1       2       2 
r3    1       2       1       2       3       87      99      2  

期望输出

    D009325 D009357 D009369 D009373 D009404 D009437 D009442 D009447 
r1    1       0       0       1       0       0       1       1               
r2    0       1       1       0       1       1       1       1        
r3    1       1       1       1       1       1       1       1    

此外,请告诉我这种方法有什么问题,是否有更好的选择

indices <- which(apply(reshapedwcw,2,function(x) x>1)) 
reshapedwcw[indices]<-1

3 个答案:

答案 0 :(得分:2)

# Create the data frame
m <- matrix(c(1, 0, 0, 2, 0, 0, 44, 78,
              0, 3, 4, 0, 2, 1, 2, 2, 
              1, 2, 1, 2, 3, 87, 99, 2), 
              nrow = 3, byrow = TRUE)

reshapedwcw <- as.data.frame(m)
colnames(reshapedwcw) <- c("D009325", "D009357", "D009369", "D009373", 
                           "D009404", "D009437", "D009442", "D009447")
rownames(reshapedwcw) <- c("r1", "r2", "r3")

# Assign 1 to data larger than 0
reshapedwcw[reshapedwcw > 0] <- 1

答案 1 :(得分:1)

只需添加0即可将二进制值转换为0/1值。您可以这样做

(reshapewcw>0)+0
#  009325 D009357 D009369 D009373 D009404 D009437 D009442 D009447 D009456 
#       1       0       0       1       0       0       1       1       0 

答案 2 :(得分:1)

你也可以这样做:

as.numeric(reshapewcw>0)

由于