1

I am working with a list, I want to loop a variable several times but I can't.

This is the example:

a=data.frame(ID=1:5,WT=1:5)  
b=data.frame(ID=101:105,WT=101:105)
c=list(a,b)
names(c)=c("P01","P02")

Now I want to add a new column to each data frame

c$P01$seq=1:length(c$P01$ID)  
c$P02$seq=1:length(c$P02$ID)

The problem that I got is that my list has 29 data frames, not two like in this example. How can I automatise this process, so I can add a new column to each data frame?

I've tried few things with no success like creating a loop, but it doesn't not work:

unique=names(c)
for (i in 1:length(unique) {
   c$unique[i]$seq=1:length(c$unique[i]$seq)  
}

2 Answers 2

1

We can use seq_along with lapply

lapply(c, transform, Seq = seq_along(ID))

Or using tidyverse

library(tidyverse)
c %>% 
   map(~ .x %>% 
            mutate(Seq = row_number()))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I've been stucked in this for a long time. Cheers
0

The reason, why your for-loop is not working, is that you are using a character-value in combination with the $-operator. You can fix this by indexing the list with [[ instead.

df_names <- names(dfs)
for (i in seq_along(df_names)) {
  dfs[[df_names[i]]]$seq <- seq_along(dfs[[df_names[i]]]$ID)
}

Further you can use the names itselves in the for-loop:

for (x in df_names) {
  dfs[[x]]$seq <- seq_along(dfs[[x]]$ID)
}

Data
Note: As c and unique are two functions in base R I changed the variable names in my example.

a <- data.frame(ID = 1:5, WT = 1:5)
b <- data.frame(ID = 101:105, WT = 101:105)
dfs <- list(a, b)
names(dfs) <- c("P01", "P02")

1 Comment

Thank you for your kind explanation about the loop. It works now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.