从下面的小 data.frame (i
) 中,我想知道如何形成以下向量 data.frame?
# Desired output (2 rows x 6 columns):
data.frame(
mpre1=c(.21,1.61) , sdpre1=c(.28,1.5) , n1 = c(21,21), #group=1,control=F,outcome= 1 & 2
mpre2=c(.12,1.13) , sdpre2=c(.25,.92) , n2 = c(16,16)) #group=2,control=T,outcome= 1 & 2
# mpre1 sdpre1 n1 mpre2 sdpre2 n2
#1 0.21 0.28 21 0.12 0.25 16
#2 1.61 1.50 21 1.13 0.92 16
从i
中提取上述向量的索引值(对于group
和outcome
)由下式给出:
rev(expand.grid(outcome = unique(i$outcome),
group = unique(i$group)))
这是一个玩具示例,非常感谢功能性 BASE R 答案。
i = read.csv("https://raw.githubusercontent.com/rnorouzian/m2/main/g.csv")
# study.name group n mpre sdpre mpos sdpos rev.sign post control outcome
#1 Diab_b 1 21 0.21 0.28 0.22 0.44 TRUE 1 FALSE 1
#2 Diab_b 1 21 0.21 0.28 0.08 0.11 TRUE 2 FALSE 1
#3 Diab_b 1 21 1.61 1.50 0.87 0.82 TRUE 1 FALSE 2
#4 Diab_b 1 21 1.61 1.50 1.97 1.04 TRUE 2 FALSE 2
#5 Diab_b 2 16 0.12 0.25 0.15 9.24 TRUE 1 TRUE 1
#6 Diab_b 2 16 0.12 0.25 0.08 0.11 TRUE 2 TRUE 1
#7 Diab_b 2 16 1.13 0.92 0.62 0.43 TRUE 1 TRUE 2
#8 Diab_b 2 16 1.13 0.92 0.84 0.55 TRUE 2 TRUE 2
最佳答案
在您的数据集中,还有一个名为“post”的变量已用于分组。
尽管如此,我想我们不想包括:
main_df <- read.csv("https://raw.githubusercontent.com/rnorouzian/m2/main/g.csv")
index <- rev(expand.grid(outcome = unique(main_df$outcome), group =unique(main_df$group)))
df_fin <- function(index){
for (i in 1:nrow(index)) {
#creating a variable of each index row(group-outcome combination)
couple <- index[i,]
#subsetting one row of combination because they also are grouped by "post" variable
subsetted_df <- subset(main_df, outcome == couple[,2] & group == couple[,1])[1,]
name <- paste0("mpre", couple[,1],couple[,2])
assign(name, subsetted_df[,'mpre'])
name1 <- paste0("sdpre", couple[,1],couple[,2])
assign(name1, subsetted_df[,'sdpre'])
name2 <- paste0("n", couple[,1],couple[,2])
assign(name2, subsetted_df[,'n'])
}
final_df <- data.frame(
mpre1 = c(mpre11, mpre12),
sdpre1 = c(sdpre11, sdpre12),
n1 = c(n11, n12),
mpre2 = c(mpre21, mpre22),
sdpre2 = c(sdpre21, sdpre22),
n2 = c(n21, n22)
)
return(final_df)
}
desired_df <- df_fin(index)
desired_df
## mpre1 sdpre1 n1 mpre2 sdpre2 n2
## 1 0.21 0.28 21 0.12 0.25 16
## 2 1.61 1.50 21 1.13 0.92 16
是你的意思吗?
关于r - 根据 Expand.grid() 给出的索引从 data.frame() 中选取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67429896/