![](/img/trans.png)
[英]Apply function to create mean for filtered columns across multiple columns r
[英]Loop to apply dyplr across multiple columns in r
我有一個數據集
outcome_data_wide_score1 <- outcome_data %>% select(group, community, site, sessions, patientid, score1) %>% arrange(sessions) %>% filter(group == 2 & province == "X") %>% pivot_wider(., names_from =sessions, values_from = c(score1))
我正在嘗試運行這些代碼為不同的分數列獲取類似的 output,如果可能的話,幾行代碼將通過一些列表或其他命令運行不同組、社區和站點的代碼
在這方面的任何幫助都將是可觀的。
使用類似於問題中發布的虛擬數據,您可以創建基於group
、 community
和site
的索引。 將其拆分為列表,將任務應用於所有分數,然后將所有內容綁定在一起。 我添加了一個 function 來執行此操作:
library(reshape2)
library(tidyverse)
set.seed(123)
#Data
df <- data.frame(group=1,community=c(rep('x',6),rep('y',3)),
site=c(rep(c('a'),3),rep(c('b'),3),rep(c('c'),3)),
patientid=c(rep(1,3),rep(2,3),rep(3,3)),
sessions=rep(c(1,2,3),3),
score1=round(runif(9,0,100),0),
score2=round(runif(9,0,100),0),
score3=round(runif(9,0,100),0),
score4=round(runif(9,0,100),0),
score5=round(runif(9,0,100),0))
#Create an id by the columns you want
df$id <- paste(df$group,df$community,df$site)
#Now split
List <- split(df,df$id)
#Function to process
myfun <- function(x)
{
#Filter columns
y <- x[,names(x)[which(grepl(c('patient|session|score'),names(x)))]]
#Melt
z <- melt(y,id.vars = c('patientid','sessions'))
#Transform
u <- pivot_wider(z, names_from =c(variable,sessions), values_from = value)
#Combine and separate
ids <- x[,'id',drop=F]
ids <- ids[!duplicated(ids$id),,drop=F]
idsg <- separate(ids,col = id,sep = ' ',into = c('group','community','site'))
#Bind
w <- bind_cols(idsg,u)
return(w)
}
#Now apply to List
List2 <- lapply(List,myfun)
#Bind all
DF <- do.call(rbind,List2)
rownames(DF)<-NULL
它將產生這個,其中分數和會話由_
分隔:
group community site patientid score1_1 score1_2 score1_3 score2_1 score2_2 score2_3 score3_1 score3_2
1 1 x a 1 29 79 41 46 96 45 33 95
2 1 x b 2 88 94 5 68 57 10 69 64
3 1 y c 3 53 89 55 90 25 4 66 71
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.