用相应的行名替换列的值

时间:2017-09-13 07:45:14

标签: r

我的数据框如下。

ID      e200 e200_cyp  e200_rad e200_obl
OTU_1    1        1        1        1
OTU_2    1        1        1        1
OTU_17   0        0        0        0
OTU_13   1        1        1        1
OTU_10   0        1        0        1
OTU_20   1        0        1        0

我想用相应的行ID替换每列的值1。 有什么帮助吗? 非常感谢你

3 个答案:

答案 0 :(得分:0)

我会将ifelseapply函数结合使用:

df <- data.frame(e200 = c(1L, 1L, 0L, 1L, 0L, 1L), 
           e200_cyp = c(1L, 1L, 0L, 1L, 1L, 0L), 
           e200_rad = c(1L, 1L, 0L, 1L, 0L, 1L), 
           e200_obl = c(1L, 1L, 0L, 1L, 1L, 0L),
           row.names = c("OTU_1", "OTU_2", "OTU_17", 
                         "OTU_13", "OTU_10", "OTU_20"))

replace_by_string <- function(x, st) {
  ifelse(x, st, "")
} 

data.frame(lapply(df, replace_by_string, rownames(df)),
           row.names=rownames(df))

答案 1 :(得分:0)

一个简单的lapply将完成这项工作。

dat[, -1] <- lapply(dat[, -1], function(x){
    x[which(as.logical(x))] <- as.character(dat$ID[which(as.logical(x))])
    x
})
dat

数据。

dat <-
structure(list(ID = structure(c(1L, 5L, 4L, 3L, 2L, 6L), .Label = c("OTU_1", 
"OTU_10", "OTU_13", "OTU_17", "OTU_2", "OTU_20"), class = "factor"), 
    e200 = c(1L, 1L, 0L, 1L, 0L, 1L), e200_cyp = c(1L, 1L, 0L, 
    1L, 1L, 0L), e200_rad = c(1L, 1L, 0L, 1L, 0L, 1L), e200_obl = c(1L, 
    1L, 0L, 1L, 1L, 0L)), .Names = c("ID", "e200", "e200_cyp", 
"e200_rad", "e200_obl"), class = "data.frame", row.names = c(NA, 
-6L))

答案 2 :(得分:0)

我们可以使用{c: df[c].unique() for c in df.columns[~df.columns.isin(['colA', 'colB'])]} dplyr包。

tidyr

数据

library(dplyr)
library(tidyr)

dt2 <- dt %>%
  gather(Group, Value, -ID) %>%
  mutate(Value = ifelse(Value == 1, ID, Value)) %>%
  spread(Group, Value)
dt2
      ID   e200 e200_cyp e200_obl e200_rad
1  OTU_1  OTU_1    OTU_1    OTU_1    OTU_1
2 OTU_10      0   OTU_10   OTU_10        0
3 OTU_13 OTU_13   OTU_13   OTU_13   OTU_13
4 OTU_17      0        0        0        0
5  OTU_2  OTU_2    OTU_2    OTU_2    OTU_2
6 OTU_20 OTU_20        0        0   OTU_20