2017-08-31 49 views
1

他是我的數據框和它的劇情[R繪圖數據幀和跟蹤因素對數轉換

my_df <- data.frame(var_1= as.factor(sample(c(0,1), 10, replace = TRUE)), 
         var_2 = sample(1:20, 10, replace = TRUE), 
         var_3 = as.factor(sample(c('a','b', 'c'), 10, replace = TRUE))) 
    plot(my_df) 

於是因素越來越轉換爲數值。如何找出因子值與其數值表示之間的映射關係?例如,它看起來像var_3有以下轉換a -> 1,b -> 2,c -> 3

我也可以在圖上顯示這個轉換圖嗎?

plot

回答

2

plot.data.frame通過...參數到?pairs具有labels參數

my_df <- data.frame(var_1= as.factor(sample(c(0,1), 10, replace = TRUE)), 
        var_2 = sample(1:20, 10, replace = TRUE), 
        var_3 = as.factor(sample(c('a','b', 'c'), 10, replace = TRUE))) 

plot(my_df, labels = LETTERS[1:3]) 

所以才讓AV標籤器以及使用

f <- function(data, default = names(data), use.varname = TRUE) { 
    default <- rep_len(default, ncol(data)) 

    sapply(seq_along(data), function(ii) { 
    x <- data[, ii] 
    if (is.factor(x)) { 
     lbl <- paste(levels(x), seq.int(nlevels(x)), sep = ' -> ', collapse = '\n') 
     if (use.varname) 
     paste(default[ii], lbl, sep = '\n') else lbl 
    } else default[ii] 
    }) 
} 

f(my_df, use.varname = FALSE) 
# [1] "0 -> 1\n1 -> 2" "var_2" "a -> 1\nb -> 2\nc -> 3" 


f(my_df, use.varname = TRUE) 
# [1] "var_1\n0 -> 1\n1 -> 2" "var_2" "var_3\na -> 1\nb -> 2\nc -> 3" 


plot(my_df, labels = f(my_df)) 

enter image description here

+0

真棒解決方案,我如何保留變量名?我正在查看你的代碼,但是我的R技能是有限的 – user1700890

+0

@ user1700890請參閱編輯,這是你的想法嗎? – rawr

+0

完美工作,最初通過警告()! – user1700890

2

一個更好的選擇可能是使用ggpairs,讓更多的信息

library(GGally) 
ggpairs(my_df) 

enter image description here

1

的整數對應於你的因子的水平。如果您想要在您的示例中報告散點圖,則可以使用軸功能簡單地設置軸的標籤。

plot(as.numeric(my_df$var_3), as.numeric(as.vector(my_df$var_1)), axes = F) 
axis(side = 1, labels = levels(my_df$var_3), at = 1:length(levels(my_df$var_3))) 
axis(side = 2) 
box() 

enter image description here

現在,如果你想多陰謀的結果,你可以做如下。

par(mfrow=c(3,3)) 
for (i in 1:ncol(my_df)){ 
    for (j in 1:ncol(my_df)){ 
    if (i == j) { 
     plot(1, cex = 0, ylim = c(0,2), xlim = c(0,2)) 
     text(1, 1, labels = paste(names(my_df)[j])) 
    } else { 
     plot(as.numeric(my_df[,i]), as.numeric(my_df[,j]), axes = F, 
      xlab = names(my_df)[i], ylab = names(my_df)[j]) 
     if (is.factor(my_df[,i])){ 
     axis(side = 1, labels = levels(my_df[,i]), at = 1:length(levels(my_df[,i]))) 
     } else { 
     axis(side = 1) 
     } 
     if (is.factor(my_df[,j])){ 
     axis(side = 2, labels = levels(my_df[,j]), at = 1:length(levels(my_df[,j]))) 
     } else { 
     axis(side = 2) 
     } 
     box() 
    } 
    } 
} 
par(mfrow=c(1,1)) 

enter image description here

絕對繁瑣,不是很漂亮,但你可以看到不同水平(類名)被保留,並在軸蜱繪製...

+0

謝謝!是否可以一次完成整個數據幀,還是需要繪製單個對? – user1700890

+0

是的,你可以。我更新了我的答案 –