0

I have a dataframe with 50 columns. I am trying to iterate through the columns in a dataframe that contain the word "apple". The dataframe contains 24 "apple" columns. If apple_1 = 1 then all the other apple_x columns in the row should equal to 1 else it shouldn't do anything.

This is my code so far:

I am successfully able to create a list of column names containing apple (excluding apple_1)

applelist<- df %>% select(contains("apple"))%>%select(!contains("apple_1"))
applelist<- list(colnames(applelist))

But when I try to loop through the columns in the applelist and update the values for each row it wants to delete the 'non' applelist columns (go from 50 columns to 24). I only want to update the apple columns and leave the rest untouched.

for (i in 1:ncol(applelist){
  df[, i] <- ifelse(df$apple_1==1, 1, df[, i])
}
aynber
  • 22,380
  • 8
  • 50
  • 63
  • It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. (A simple example with 5 columns rather than 50 would be fine) – MrFlick Aug 31 '22 at 15:03

1 Answers1

0

Here, applelist is a list of length 1. i.e. what we are getting is

applelist <- list(c('a', 'b', 'c'))

We just need to extract the names as a vector or if we need a list, use as.list (not really needed here)

library(dplyr)
nm1 <- df %>% 
     select(contains("apple"))%>%
     select(!contains("apple_1")) %>% 
     names

Then use

for(nm in nm1) {df[[nm]] <- ifelse(df$apple_1 == 1, 1, df[[nm]]}

In addition, a tidyverse option would be

df <- df %>%
     mutate(across(all_of(nm1), ~ ifelse(apple_1 == 1, 1, .x))
akrun
  • 874,273
  • 37
  • 540
  • 662