R:for循环,每次遍历一个 Dataframe 的n列

y1aodyip  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(259)

需要帮助来解决此问题。我有下面的数据框,其中Grp是我的ID列,列AI是我的数值变量。数据框中的数值列数可以不同。它可以从5到500甚至更多。

data <- data.frame("Grp" = rep(c("GRP_A1", "GRP_A2", "GRP_A3", "GRP_A4", "GRP_A5"), each = 5),
  A = rep(1:5, each = 5), 
  B = rep(6:10, each = 5), 
  C = rep(11:15, each = 5), 
  D = rep(16:20, each = 5),
  E = rep(21:25, each = 5), 
  G = rep(26:30, each = 5), 
  H = rep(31:35, each = 5),
I = rep(36:40, each = 5))

> head(data)
     Grp A B  C  D  E  G  H  I  J  K
1 GRP_A1 1 6 11 16 21 26 31 36 41 51
2 GRP_A1 1 6 11 16 21 26 31 36 41 51
3 GRP_A1 1 6 11 16 21 26 31 36 41 51
4 GRP_A1 1 6 11 16 21 26 31 36 41 51
5 GRP_A1 1 6 11 16 21 26 31 36 41 51
6 GRP_A2 2 7 12 17 22 27 32 37 42 52

我有一个条件,比如说n

n <- 3

我要找的是
1.运行for循环,对n连续列进行一些计算,然后与我的ID列沿着进行子集化**组。**在每个循环中选择ID和n列,运行计算
1.将每个新创建的df保存为csv文件。
目前我就是这样做的,这是不可持续的。

任何帮助我都感激不尽

n <- 3

df1 <- data %>%
  select(1, 2:4) %>%
  pivot_longer(cols = 2:4, names_to = "Trait", values_to = "Value")
write.csv(df1, "DF1.csv", row.names = F)

df2 <- data %>%
  select(1, 5:7) %>%
  pivot_longer(cols = 2:4, names_to = "Trait", values_to = "Value")
write.csv(df2, "DF2.csv", row.names = F)

df3 <- data %>%
  select(1, 8:9) %>%
  pivot_longer(cols = 2:3, names_to = "Trait", values_to = "Value")
write.csv(df3, "DF3.csv", row.names = F)
6za6bjd0

6za6bjd01#

比如:

i <- 1
n <- 3
startCol <- 2
endCol <- startCol + n - 1
stopNow <- FALSE
while(!stopNow) {
  if (endCol == data %>%  ncol())  stopNow <- TRUE
  tmp <- data %>% 
           select(all_of(c(1, startCol:endCol))) %>% 
           pivot_longer(
             cols = startCol:endCol, 
             names_to = "Trait", 
             values_to = "Value"
           )
  write.csv(tmp, file.path(paste0("DF", i), ".csv"), row.names = F)
  startCol <- endCol + 1
  endCol <- startCol + n - 1
  if (endCol > data %>% ncol()) endCol <- data %>% ncol()
  i <- i + 1
}

尽管我希望列名中有一些结构,这会使这更容易。

相关问题