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

标签 r dplyr

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

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/

相关文章:

r - dplyr - 使用列索引而不是列名称将列输入到 rowwise()

r - 将 fiddle 图放在两侧,并在 R ggplot 中与组平均值建立一条线

r - 将函数应用于每一行数据框并返回数据框列表的有效方法

Rscript - 摆脱 "WARNING: ignoring environment value of R_HOME"

r - 如何抑制 R 脚本中函数的消息?

r - 使用 dplyr() 检索通过 group_by() 和 do() 创建的模型对象

r - 将 purrr 和 ggplot 与 group_by 和 Nest() 结合使用时获取绘图标题

R 包 : RCurl and curl packages install failure on Linux

sql - 当结果集很大时,RODBC 会丢失日期时间的时间值

r - 当 x 发生时如何将 tibble 从日期表转换为具有 x 的分类数据的日期表