Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

how to avoid repeated codes in R

I am creating 2 data frames and merging them. I have created duplicate codes below, Since I am new in R programming I want the same results without creating repeated codes.


     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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have a look at 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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...