Home > Net >  Cannot append a vector inside a list in R
Cannot append a vector inside a list in R

Time:09-26

I have a set of vectors inside a list wherein I want to append certain values to each vector. When I used append() outside the loop, it worked perfectly fine but inside a loop it doesn't seem to work.

factors <- list(c("K3BG","9"),c("RTCKO","4"))
len <- length(factors)
for (i in 1:length)
{
    rejig_score <- factors[[i]][2]
    rejig_score <- as.numeric(rejig_score)
    if(rejig_score > 5)
    {
         factors[[i]] <- append(factors[[i]],"Approved")
    }
    else
    {
        factors[[i]] <- append(factors[[i]],"Disapproved")
    }
}

Can someone guide where I'm going wrong.

Thank you for your help

CodePudding user response:

I changed 1:lenght to 1:len inside for

factors <- list(c("K3BG","9"),c("RTCKO","4"))

len <- length(factors)

for (i in 1:len)
{
  rejig_score <- factors[[i]][2]
  rejig_score <- as.numeric(rejig_score)
  if(rejig_score > 5)
  {
    factors[[i]] <- append(factors[[i]],"Approved")
  }
  else
  {
    factors[[i]] <- append(factors[[i]],"Disapproved")
  }
}

factors

[[1]]
[1] "K3BG"     "9"        "Approved"

[[2]]
[1] "RTCKO"       "4"           "Disapproved"

CodePudding user response:

Using lapply

lapply(factors, function(x) c(x, if(as.numeric(x[2]) > 5) 
      "Approved" else "Disapproved"))

-output

[[1]]
[1] "K3BG"     "9"        "Approved"

[[2]]
[1] "RTCKO"       "4"           "Disapproved"

Or another option is to extract the second element from the list and do the comparison outside, create the vector values and append

new <- c("Disapproved", "Approved")[1   
       (as.numeric(sapply(factors, `[[`, 2)) > 5)]
 Map(c, factors, new)
[[1]]
[1] "K3BG"     "9"        "Approved"

[[2]]
[1] "RTCKO"       "4"           "Disapproved"
  •  Tags:  
  • r
  • Related