Home > Back-end >  R - How to write in specific column in a loop : nothing comes out
R - How to write in specific column in a loop : nothing comes out

Time:09-10

I'm working on a R program to automatically write a text in specific cell, in specific rows while being in a loop.

The each d$data.frame is cut into a maximum of 150 rows The aim is to divide the document into 3 sections of 50 rows to put a name in column number 5. (made to give a task to someone specific)

What we have is :

d: a list of data.frames done by splitting a huge data base

  • w: length of d $
for (i in 1:w)  {
  if   (nrow(102<d[[i]])&nrow(d[[i]])<150){
    d[[i]][1:50,c("Contact Owner")] <- 'Luc'  
    d[[i]][51:101,c("Contact Owner")] <- 'Bertha'
    d[[i]][102:150,c("Contact Owner")] <- 'Marc'
  } else 
    if (nrow(51<d[[i]])&nrow(d[[i]])<101){
      d[[i]] [1:50,c("Contact Owner")] <- 'Luc'
      d[[i]] [51:101,c("Contact Owner")] <- 'Bertha'
    } else 
      if  (nrow(1<d[[i]])&nrow(d[[i]])<50){
        d[[i]] [1:nrow(d[[i]]),c("Contact Owner")] <- 'Luc'}
break
  }

I keep on having this error message argument is of length zero

thank you in advance for all the help :)


More informations


I can't shqre the files I'm working on as they are private data but here are the current details I can give

  • d is a list of 5 data.frame that was given by `d <- split(Scrapping,r)

d$1, d$2, d$3, d$4 are 150x16 d$5 is 10x16`

In the 5th column of each d$i I want to write names row 1 -50: I would like Luc row 51 -101: Bertha row 102 -150: Marc

Yet the last d$i data.frame will often be less than 150 rows, so I want to put only names where there are other data.

CodePudding user response:

Here is an easier option with split after creating a grouping vector with gl

d1 <- transform(d, newcol = paste0('name', as.integer(gl(nrow(d), 50, nrow(d)))))
split(d1, d1$newcol)

CodePudding user response:

I was able in the end to find a way to do so like this :

w <- length(d)
for (i in 1:w)  {
  d[[i]][1:50,c("Contact Owner")] = "Luc"  
  d[[i]][51:101,c("Contact Owner")] = "Bertha"
  d[[i]][102:150,c("Contact Owner")] = "Marc"
  d[[i]] <- with(d[[i]], d[[i]][!(`First Name` == "" | is.na(`First Name`)), ])   
}```
  • Related