2017-09-08 20 views
0

我希望這個問題對於這個論壇來說不太容易(實際上,我在這裏問這個問題幾乎有些尷尬,但是我對整個這個小問題很感興趣一天......)在繪製R之前標籤變量的函數

我dataframes如下所示:

df <- data.frame(runif(4), 
      c("po", "pr", "po", "pr"), 
      c("Control 1","Control 1", "Treatment 1", "Treatment 1")) 

names(df) <- list("values", "test_type", "group") 

現在,我想以後easliy重新標籤變量「test_type」和「組」的陰謀。 (這是更好的閱讀「預測試」,而不是在演示:-)「PR」) 我可以做手工:

df$test_type <- factor(df$test_type, 
        levels = c("pr", "po"), 
        labels = c("pretest", "posttest")) 
df$group <- factor(df$group, 
       levels = c("Control 1", "Treatment 1"), 
       labels = c("control", "EST")) 

在這種情況下,我不得不重複這對於很多更dataframes ,這導致我寫一個功能:

var_label <- function(df, test, groups){ 

# Create labels 
df$test_type <- factor(df$test, 
        levels = c("pr", "po"), 
        labels = c("pretest", "posttest")) 
df$group <- factor(df$groups, 
       levels = c("Control 1", "Treatment 1"), 
       labels = c("control", "EST")) 

return(list(df$test_type, df$group)) 
} 

不幸的是,這是行不通的。我嘗試了很多不同的版本,並且從Hmisc軟件包中獲得了不同的命令,但是這些都沒有奏效。我知道,我可以用另一種方式解決這個問題,但是我試着編寫更高效,更短的代碼,並且真的很感興趣,爲了使這個功能起作用,我必須改變。或者甚至更好,你有一個更有效的方法的建議?

非常感謝您提前!

+2

您需要閱讀'help(「$」)''。 – Roland

+1

你看過'?forcats :: fct_relabel'嗎? – joemienko

回答

0

正如我上面提到的,我認爲forcats::fct_relabel()是你想要的,以及dplyr::mutate_at()。假設您的重新標籤需求不會比您的問題中列出的更復雜,那麼下面的內容應該能讓您看到您期望的內容。

####BEGIN YOUR DATAFRAME CREATION#### 
df <- data.frame(runif(4), 
       c("po", "pr", "po", "pr"), 
       c("Control 1","Control 1", "Treatment 1", "Treatment 1")) 

names(df) <- list("values", "test_type", "group") 
#####END YOUR DATAFRAME CREATION##### 

# Load dplyr and forcats 
library(dplyr) 
library(forcats) 

# create a map of labels and levels based on your implied logic 
# the setup is label = level 
label_map <- c("pretest" = "pr" 
       ,"posttest" = "po" 
       ,"control" = "Control 1" 
       ,"EST" = "Treatment 1") 

# create a function to exploit the label map 
fct_label_select <- function(x, map) { 
    names(which(map == x)) 
} 

# create a function which is responsive to a character vector 
# as required by fct_relabel 
fct_relabeler <- function(x, map) { 
    unlist(lapply(x, fct_label_select, map = map)) 
} 

fct_relabeler(levels(df$test_type), map = label_map) 

# function to meet your apparent needs 
var_label <- function(df, cols, map){ 
    df %>% 
    mutate_at(.vars = cols 
       ,.funs = fct_relabel 
       ,fun = fct_relabeler 
       ,map = map) 
} 

var_label(df = df, cols = c("test_type", "group"), map = label_map) 

# values test_type group 
# 1 0.05159681 posttest control 
# 2 0.89050323 pretest control 
# 3 0.42988881 posttest  EST 
# 4 0.32012811 pretest  EST 
+0

非常感謝您的幫助!這是我期待的!我還不知道forcats軟件包,但這工作正常。 – user6925545