gpt4 book ai didi

r - 使用递增变量循环并改变多个列

转载 作者:行者123 更新时间:2023-12-04 00:00:12 24 4
gpt4 key购买 nike

我的目标是在一行代码中执行多列操作,而不用硬编码变量名。

structure(list(Subject = 1:6, Congruent_1 = c(359, 391, 384, 
316, 287, 403), Congruent_2 = c(361, 378, 322, 286, 276, 363),
Congruent_3 = c(342, 355, 334, 274, 297, 335), Congruent_4 = c(365,
503, 324, 256, 266, 388), Congruent_5 = c(335, 354, 320,
272, 260, 337), Incongruent_1 = c(336, 390, 402, 305, 310,
400), Incongruent_2 = c(366, 407, 386, 280, 243, 393), Incongruent_3 = c(323,
455, 317, 308, 259, 325), Incongruent_4 = c(361, 392, 357,
274, 342, 350), Incongruent_5 = c(300, 366, 378, 263, 258,
349)), row.names = c(NA, 6L), class = "data.frame")

我的数据 looks like this .

我需要进行列减法并将这些新值保存到新列中。例如,名称为 selhist_1 的新列应计算为 Incongruent_1 - Congruent_1。我尝试编写一个 for 循环,通过名称索引现有列并使用相同的索引变量创建新列:

for(i in 1:5)(
DP4 = mutate(DP4, as.name(paste("selhistB_",i,sep="")) = as.name(paste("Incongruent_",i,sep="")) - as.name(paste("Congruent_",i,sep="")))
)

但我收到了这个错误:

Error: unexpected '=' in: "for(i in 1:5)( DP4 = mutate(DP4, as.name(paste("selhistB_",i,sep="")) ="

我宁愿使用这种模块化方法,而不是使用 mutate() 函数进行硬编码和写出五次“selhistB = incongruent_1 - congruent_1”。

我也想知道我是否可以在这个数据的长版本上实现相同的目标,也许它会更有意义。

最佳答案

library(dplyr)

d %>%
pivot_longer(-Subject,
names_to = c(".value", "id"),
names_sep = "_") %>%
mutate(selhistB = Incongruent - Congruent) %>%
pivot_wider(names_from = id, values_from = c(Congruent, Incongruent, selhistB))

或者只是跳过最后一个枢轴,并保持一切都很长。

关于r - 使用递增变量循环并改变多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62810207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com