I'm trying to replace multiple columns of a large data frame based with indexing. What I want/have done so far combines this post and this post. Let me provide the example for clarity.
Here is much simplified sample data in dput format:
DF <-
structure(list(Fruits = structure(c(1L, 3L, 4L, 2L),
.Label = c("Apples", "Avocado", "Oranges", "Pineapple"),
class = "factor"), Weight2 = c(20L, 15L, 40L, 60L),
Weight = c(2L, 4L, 8L, 5L), `Number` = c(10L,
16L, 6L, 20L)), class = "data.frame", row.names = c(NA, -4L))
Fruits Weight Weight2 Number
Apples 20 2 10
Oranges 15 4 16
Pineapple 40 8 6
Avocado 60 5 20
What I want to do is for DF, given a list of Fruits, change the columns Weight and Weight2 to N. I'll mention that my DF is actually a list of data frames and my list is a list of lists so indexing is needed. Here is my code so far:
fruit.to.change <- c("Apples","Pineapple")
DF$Weight[which(DF$Fruits == fruit.to.change)] <- "N" #change the first column but I want to change multiple columns.
colID <- grepl("Weight", names(DF))
which(DF$Fruits %in% fruit.to.change[1:length(fruit.to.change)]) #gets the positions matching
But not sure how to select and replace the columns in colID
? I'm sure it's just another level of indexing but can't figure it out. I basically want something like DF$Weight:Weight2 [which(DF$Fruits %in% fruit.to.change )] <- "N"
Thanks VERY much.