循环 str_c( ) 函数以按 1 - 100 的顺序连接列

问题描述 投票:0回答:1

我在 R 中有一个数据框(标题为 fy14bx)。

我需要将标题为“onset1”、“onset2”、“onset3”...“onset100”的 100 列与标题为“x08ddx1”...“x08ddx100”的相应列连接起来,生成新列“c1”-“c100”

我正在使用 stingr,具体来说:

fy14bx$c1 <- str_c(fy14bx$onset1, "-", fy14bx$x08ddx1)

显然我不想手动执行此操作(我需要在其他 8 个数据帧(fy15...等)中执行此操作,其中列名称也略有不同)。

有人可以帮我吗?

谢谢

这没有用

for (i in 1:100) {
  col_name <- paste0("c", i)
  fy14bx[, col_name] <- str_c(fy14bx[, paste0("onset", i)], "-", fy14bx[, paste0("x08ddx", i)])
}
r loops concatenation
1个回答
0
投票

您的代码只需稍作调整即可按预期工作:

library(tidyverse)

fy14bx <- data.frame(onset1 = c(1,2,3,4),
                     onset2 = c(5,6,7,8),
                     onset3 = c(9,10,11,12),
                     x08ddx1 = c(101, 102, 103, 104),
                     x08ddx2 = c(105, 106, 107, 108),
                     x08ddx3 = c(109, 110, 111, 112))

fy14bx$c1 <- str_c(fy14bx$onset1, "-", fy14bx$x08ddx1)
fy14bx
#>   onset1 onset2 onset3 x08ddx1 x08ddx2 x08ddx3    c1
#> 1      1      5      9     101     105     109 1-101
#> 2      2      6     10     102     106     110 2-102
#> 3      3      7     11     103     107     111 3-103
#> 4      4      8     12     104     108     112 4-104

for (i in 1:3) {
  fy14bx[[paste0("c", i)]] <- str_c(fy14bx[, paste0("onset", i)], "-", fy14bx[, paste0("x08ddx", i)])
}

fy14bx
#>   onset1 onset2 onset3 x08ddx1 x08ddx2 x08ddx3    c1    c2     c3
#> 1      1      5      9     101     105     109 1-101 5-105  9-109
#> 2      2      6     10     102     106     110 2-102 6-106 10-110
#> 3      3      7     11     103     107     111 3-103 7-107 11-111
#> 4      4      8     12     104     108     112 4-104 8-108 12-112

创建于 2023-09-26,使用 reprex v2.0.2

这是你期望的结果吗?

© www.soinside.com 2019 - 2024. All rights reserved.