R:使用(嵌套)循环编写具有特定列组合的输出文件
我有以下数据框:R:使用(嵌套)循环编写具有特定列组合的输出文件,r,loops,R,Loops,我有以下数据框: IID.m IID.f score.m measure.m health.m score.f measure.f health.f 1 2 120 80 8 131 82 5 3 4 121 83 9 119 80 7 5 6 133 78 5 121 87 9 7 8 126 87 8 120 83 4 因此,两个ID(比如,父亲=IID.m,母亲=IID.f)和三个变量属于第一个ID(score.m,measure.m和health.m),之后的三个变量属于第二个ID
IID.m IID.f score.m measure.m health.m score.f measure.f health.f
1 2 120 80 8 131 82 5
3 4 121 83 9 119 80 7
5 6 133 78 5 121 87 9
7 8 126 87 8 120 83 4
因此,两个ID(比如,父亲=IID.m,母亲=IID.f)和三个变量属于第一个ID(score.m,measure.m和health.m),之后的三个变量属于第二个ID(score.f,measure.f和health.f)
我需要生成以下由四列组成的输出文件:
文件1:
score.m health.f health.m score.f
文件2:
measure.m health.f health.m measure.f
文件3:
measure.m score.f score.m measure.f
换言之:父亲和母亲的三个变量中有两个,顺序为“父亲变量1”、“母亲变量2”、“父亲变量2”、“母亲变量1”。对于所有变量组合,这些文件需要是单独的以制表符分隔的输出文件
在这种情况下,这意味着只有三个不同的输出文件,因为只有三个不同的组合(分数+健康、度量+健康、度量+得分)。实际上,我有更多的变量,有更多可能的组合,这就是为什么我怀疑我需要for循环(或者for循环中的for循环?)。如何在R中做到这一点?考虑运行
combn
以获得得分、度量和健康列指数的所有组合。然后在lappy
中运行该返回列表以构建子集数据帧。但是,您不需要所有组合,只需要在f和m之间匹配的地方,所以在dataframe列表上运行一个过滤器
,特别是运行另一个combn
,为grep
调用构建变量配对
数据
txt = 'IID.m IID.f score.m measure.m health.m score.f measure.f health.f
1 2 120 80 8 131 82 5
3 4 121 83 9 119 80 7
5 6 133 78 5 121 87 9
7 8 126 87 8 120 83 4'
df <- read.table(text = txt, header = TRUE)
txt='IID.m IID.f score.m measure.m health.m score.f measure.f health.f
1 2 120 80 8 131 82 5
3 4 121 83 9 119 80 7
5 6 133 78 5 121 87 9
7 8 126 87 8 120 83 4'
非常感谢!您是否有一个过滤器命令的替代方案,在其中我不必详细说明组合?在我的实际数据集中还有很多…有关所有唯一变量对,请参阅运行另一个combn
的更新。
value_combos <- combn(3:ncol(df), 4, simplify = FALSE)
df_list <- lapply(value_combos, function(i) df[, i])
col_pairs <- lapply(combn(unique(gsub("\\.m|\\.f", "", names(df)[-2:-1])), 2, simplify = FALSE),
function(i) paste(i, collapse="|"))
col_pairs
# [[1]]
# [1] "score|measure"
# [[2]]
# [1] "score|health"
# [[3]]
# [1] "measure|health"
sub_df_list <-lapply(col_pairs, function(x)
Filter(function(d) length(grep(x, names(d))) == 4 , df_list)[[1]])
sub_df_list
# [[1]]
# score.m measure.m score.f measure.f
# 1 120 80 131 82
# 2 121 83 119 80
# 3 133 78 121 87
# 4 126 87 120 83
# [[2]]
# score.m health.m score.f health.f
# 1 120 8 131 5
# 2 121 9 119 7
# 3 133 5 121 9
# 4 126 8 120 4
# [[3]]
# measure.m health.m measure.f health.f
# 1 80 8 82 5
# 2 83 9 80 7
# 3 78 5 87 9
# 4 87 8 83 4
# OUTPUT TAB-DELIMITED FILES FROM LIST
lapply(seq_along(sub_df_list), function(i)
write.table(sub_df_list[[i]], file = paste0("Output", i, ".txt"), sep="\t"))