Home > Software engineering >  Is there a for loop that can add a column to my dataframes?
Is there a for loop that can add a column to my dataframes?

Time:06-04

I'm trying to add a column to my data 19 data frames to give IDs to each, so I can combine all 19 into one and have IDs listed. I want to make raster plots with all of them together, so I need to combine the data.

This is how I accomplished it individually, but making 19 values seems tedious.

XCB1 <- read.delim("logXCB1.txt", skip= 41,header = TRUE, sep= "|", stringsAsFactors = TRUE)

ID<- c("XCB1")

XCB1 <- data.frame(XCB1, ID)

CodePudding user response:

We could use lapply to loop over all the .txt files from the folder, read with read.delim and keep it in a list

files <- list.files('path/to/your/folder', pattern = "\\.txt$", full.names = TRUE)
lst1 <- lapply(files, read.delim, skip = 41, header = TRUE, sep = "|")
nm1 <- gsub("log|\\.txt", "", basename(files))
lst1 <- Map(cbind, lst1, ID = nm1)

Or with tidyverse

library(purrr)
library(dplyr)
lst1 <- map2(files, nm1, ~ read.delim(.x, skip = 41, sep = "|") %>%
                     mutate(ID = .y))
# if we need only a single data by rbinding
out <- bind_rows(lst1)

CodePudding user response:

With these example data

x <- list(data.frame(v=1:2), data.frame(v=11:12))

You can achieve that like this

ids <- c("a", "b", "c")
y <- lapply(seq_along(x), \(i) cbind(ID=ids[i], x[[i]]))

z <- do.call(rbind, y)
z
#  ID  v
#1  a  1
#2  a  2
#3  b 11
#4  b 12
  •  Tags:  
  • r
  • Related