【问题标题】:how to avoid repeated codes in R如何避免R中的重复代码
【发布时间】:2021-04-13 07:24:27
【问题描述】:

我正在创建 2 个数据框并将它们合并。我在下面创建了重复的代码,因为我是 R 编程新手,所以我想要相同的结果而不创建重复的代码。


     category sex day   flag     value       mean        Standard deviation
1        FC   F   -1          a     17.2     17.01333             0.9463212
2        FC   F   -1          a     17.0     17.01333             0.9463212
3        FC   F   -1          a     18.7    17.01333              0.9463212
4        FC   F   -1          a     17.1    17.01333             0.9463212
5        FC   F   -1          a     17.2    17.01333             0.9463212
6        FC   F   -1          a     17.2    17.01333             0.9463212

library(dplyr)
library(plyr)
library(doBy)
library(tidyverse)
data <- read.csv("users/study.csv")
print(data)

new_table <- select(data, category, sex, day, flag,value)
target1 <- "a"
target2<-"b"

#Repeated Codes
filtered1<-filter(new_table, sex=="F", category=="FC",flag %in% target1,day==-1)
filtered1
filtered2<-filter(new_table, sex=="F", category=="FC",flag %in% target2,day==-1)
filtered2

result1<-filtered1 %>%
  mutate(mean = mean(value),
         `Standard deviation` = sd(value))
result2<-filtered2 %>%
  mutate(mean = mean(value),
         `Standard deviation` = sd(value))

#Merging the dataframes
dataframe<-do.call("rbind", list(result1,result2))
dataframe

【问题讨论】:

  • SexFC 是否分别具有FFC 以外的值?
  • 是的,它具有 F 和 FC 以外的值,我想过滤此列中的每个值并获取结果。但是由于FC有更多的值,应该如何在过滤时不硬编码值来完成
  • 您可能希望对每个此类值组合进行这些计算?
  • 是的,你是对的
  • 是的,我必须过滤多个组合。例如在“类别”和“标志”中

标签: r


【解决方案1】:

看看group_by()

library(tidyverse)

results <- new_table %>%
  subset(sex=="F" & category=="FC" & day==-1) %>%
  group_by(flag) %>%
  mutate(mean=mean(value),
         `Standard deviation` = sd(value))

【讨论】:

  • 我觉得你应该试试new_table %&gt;% filter(day==-1) %&gt;% group_by(sex, category, flag) %&gt;% summarise(mean = mean(value), SD = sd(value))
  • 罗曼是对的!如果您想要每种组合的均值和标准差,您应该使用他的答案。
【解决方案2】:

我想你可能想要这两个中的任何一个

new_table %>%
  group_by(sex, category, flag, day) %>%
  mutate(mean = mean(value),
         standardDeviation = sd(value))

new_table %>%
  group_by(sex, category, flag, day) %>%
  summarise(mean = mean(value),
         standardDeviation = sd(value))

【讨论】:

  • 但我必须过滤多个组合。例如在“类别”和“标志”中
猜你喜欢
  • 2011-08-29
  • 1970-01-01
  • 2020-08-31
  • 2012-06-19
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多