2017-09-13 10 views
1

次のようなデータフレームがあります。列の値を対応する行の名前に置き換えます。

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 

すべての列の値1を対応する行IDで置き換えたいとします。 助けてください? は非常に

答えて

0

をありがとう、私はapply機能と組み合わせてifelseを使用します。

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)) 
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)) 
+0

ありがとうございました。その作業:) – Ushi

0

我々はdplyrtidyrパッケージを使用することができます。

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 

データ

dt <- read.table(text = "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", 
       header = TRUE, stringsAsFactors = FALSE) 
関連する問題