简体   繁体   中英

Removing Columns in one data frame based on values of another - conditional looping

Hi so I am having issues looping through my data frame and removing columns based on the condition that suppress = 1. So the loop would need to go through every column of df1 and remove the columns suppress = 1 for that same variable. It would need to determine that the specific row of suppress = 1 has the same variable in both df's.

So there are two data frames. df1 contains all the data and df2 contains the conditions based on the variables of df1.

df1 <- data.frame("ID" = c(1,2,3,4,5), "Age" = c(19,50,46,32,28))

df2 <- data.frame("Variable" = c("ID", "Age"), "Suppress" = c(1,0))

The main issue I am having is that the loop I currently have works for when I make a data frame such as df1 and df2, but not for when I import a csv file and use that data.

Could it be the format of the data frames or does the loop need to be adjusted to work for the csv imports? I suspect the latter.

Here is the loop I currently have:

for(i in names(df1)){
   if(df2$Variable == names(df1[i]) & df2$Suppress == 1){
      df1[i] <- NULL
   }
}

Another version... essentially the same

for(i in names(df1)){
   if(df2$Variable %in% names(df1[i]) & df2$Suppress == 1){
      df1[i] <- NULL
   }
}

I cannot post a csv here, but I recommend trying to run the above code with an imported csv file similar to df1 and df2.

Note: Both the df1 and df2 are being imported as a csv file.

Recap: Why does the current loop not work with imported csv data and what are alternative ways to removing the columns based on df2's suppress variable.

Thanks

I believe the logic in your posted code is not right, you should be comparing each value of df2$Variable to names(df1) .

for(i in seq_along(nrow(df2))){
  if(df2$Variable[i] %in% names(df1) && df2$Suppress[i] == 1){
    df1[i] <- NULL
  }
}

df1
#  Age
#1  19
#2  50
#3  46
#4  32
#5  28

A vectorized way, with no loops at all is the following.

inx <- (names(df1) %in% df2$Variable) & (df2$Suppress == 1)
df1[!inx]
#  Age
#1  19
#2  50
#3  46
#4  32
#5  28

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM