Home > Enterprise >  How to conditionally remove columns in r?
How to conditionally remove columns in r?

Time:10-01

I would like to remove for each row, the column that has the "o" value.
For example: in row 3 delete the first and third columns and keep the second with the name as it is.

> stocks_grid2
  Var1 Var2 Var3
1    o    o    o
2 Var1    o    o
3    o Var2    o
4 Var1 Var2    o
5    o    o Var3
6 Var1    o Var3
7    o Var2 Var3
8 Var1 Var2 Var3

reproductible data

n_s <- 3
l_s <- rep(list(0:1), n_s)
stocks_grid2 <- expand.grid(l_s)

stocks_grid2[-1] <- lapply(seq_along(stocks_grid2)[-1], function(x) ifelse(stocks_grid2[[x]] == 1, names(stocks_grid2)[x], stocks_grid2[[x]]))
stocks_grid2[1] <- lapply(seq_along(stocks_grid2)[1], function(x) ifelse(stocks_grid2[[x]] == 1, names(stocks_grid2)[x], stocks_grid2[[x]]))

stocks_grid2[-1] <- lapply(seq_along(stocks_grid2)[-1], function(x) ifelse(stocks_grid2[[x]] == 0, "o", stocks_grid2[[x]]))
stocks_grid2[1] <- lapply(seq_along(stocks_grid2)[1], function(x) ifelse(stocks_grid2[[x]] == 0, "o", stocks_grid2[[x]]))

the output would look like

  Var2
3 Var2

for each row

CodePudding user response:

The overall goal of the question is not clear but assuming you are applying some code in a loop you can try -

for(i in seq(nrow(stocks_grid2))) {
  row <- stocks_grid2[i, ]
  result <- row[row != 'o']
  #Use `result` for further processing if needed.
  print(result)
}

#character(0)
#[1] "Var1"
#[1] "Var2"
#[1] "Var1" "Var2"
#[1] "Var3"
#[1] "Var1" "Var3"
#[1] "Var2" "Var3"
#[1] "Var1" "Var2" "Var3"

CodePudding user response:

I'm not sure but is this what you want?

apply(df, 1, function(x) {
  x[x!= "o"]
  
})

result:

[[1]]
named character(0)

[[2]]
  Var1 
"Var1" 

[[3]]
  Var2 
"Var2" 

[[4]]
  Var1   Var2 
"Var1" "Var2" 

[[5]]
  Var3 
"Var3" 

[[6]]
  Var1   Var3 
"Var1" "Var3" 

[[7]]
  Var2   Var3 
"Var2" "Var3" 

[[8]]
  Var1   Var2   Var3 
"Var1" "Var2" "Var3"
  • Related