2017-09-08 22 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