如何用R

时间:2019-04-30 09:30:36

标签: r

我有一个数据表stats.marks2,它有4个变量,即"Subject", "Variable", "Sem1", "Sem2"

在“变量”下,字符值为"n_", "mean_", "sd_", "q1_", "median_", "q3_", "minmax"

我必须替换

"n_" by "n", 
"mean_" by "Mean", 
"sd_" by "SD", 
"q1_" by "Q1",
"median_" by "Median", 
"q3_" by "Q3" and 
"minmax" by "Min, Max".

我该怎么做?

1 个答案:

答案 0 :(得分:0)

对数据样本表示感谢。

使用stringrdplyr并假设stats.marks2是您的数据:

stats.marks2 %>% mutate(Variable = str_to_upper(str_replace(Variable, '_', '')))

编辑:由于对于单个模式而言,您想要做的事情太复杂了,因此让我们使用str_replace_all

中的数组来定义每个替换项
stats.marks3 %>%
  mutate(Statistics = str_replace_all(Statistics, 
                                      c("n_" = "n",
                                        "mean_" = "Mean",
                                        "sd_" = "SD",
                                        "q1_" = "Q1",
                                        "median_" = "Median",
                                        "q3_" = "Q3",
                                        "minmax" = "Min, Max")
                                      ))