j235
j235

Reputation: 150

Add value respectively in each column data.frame

I have list which contain 12 data.frame. Each of this data frame is from January to December. This is how look like my list with name Sheet_list in R Studio.

enter image description hereName Type

So my question is how to put additional column in each of these tables with the appropriate month? Е.g for January, 1 etc.

Can somebody help me?

Upvotes: 2

Views: 106

Answers (2)

Raja Saha
Raja Saha

Reputation: 509

If you don't want to use any external packages try:

l <- list(january=data.frame(id=c(1,2)),
          february=data.frame(id=c(3,4,5)))

lapply(names(l), function(x){
  l[[x]]$month <<- x
  return(NULL)
})

l
# $`january`
#   id   month
# 1  1 january
# 2  2 january
# 
# $february
#   id    month
# 1  3 february
# 2  4 february
# 3  5 february

Upvotes: 1

Nicolas2
Nicolas2

Reputation: 2210

Possibly:

library(purrr)
library(dplyr)
l <- list(january=data.frame(id=c(1,2)),
         february=data.frame(id=c(3,4,5)))

l <- purrr::imap(l,function(x,y) mutate(x,month=y))
l
#$`january`
#  id   month
#1  1 january
#2  2 january
#
#$february
#  id    month
#1  3 february
#2  4 february
#3  5 february

Upvotes: 2

Related Questions