Home > Software engineering >  Multiply values of some columns of a data frame within a date range and based on the values of anoth
Multiply values of some columns of a data frame within a date range and based on the values of anoth

Time:10-25

I am struggling with an ifelse statement in R. I have a data frame with 64 columns and 12861 rows. I need to multiply 10 of those columns within a date range (date is a column) and based on the value in another row (tdiff) and replace the old values with the new values in the data frame. This line of code results in a dataframe that is 12681 X 12681. It should be the original size of 12681 (rows) by 64 (columns). What am I doing wrong? Thank you in advance!

test<-data.frame(ifelse(slopejoin$tdiff==2 & slopejoin$date>="2021-01-30" & slopejoin$date<="2021-08-08",
     slopejoin[,c("a_Pinene","Isoprene","Methyl_Vinyl_Ketone","Nopinone","Benzene_", "D_Limonene",
                  "Sabinene","a_Cedrene","Pentane","Hexane")]*0.85,
     slopejoin[,c("a_Pinene","Isoprene","Methyl_Vinyl_Ketone", "Nopinone","Benzene_", "D_Limonene",
                  "Sabinene","a_Cedrene","Pentane","Hexane")]))

Edit: I took the first commentor's suggestion but wanted to add one more condition but received an error: "Error in cols & slopejoin$substr != z : operations are possible only for numeric, logical or complex types." Here is the code I am using:

cols <- c("a_Pinene","Isoprene","Methyl_Vinyl_Ketone", "Nopinone","Benzene_", "D_Limonene", "Sabinene","a_Cedrene","Pentane","Hexane")
x <- "2021-01-06"
y <- "2021-08-08"
z <- 'zero_VOC_2'

slopejoin[slopejoin$tdiff == 2 & slopejoin$date >= x & slopejoin$date <= y,cols & slopejoin$substr != z] <- slopejoin[slopejoin$tdiff == 2 & slopejoin$date >= x & slopejoin$date <= y,cols & slopejoin$substr != z] * 0.06

Not quite sure where the error comes from. First I was thinking of a class issue but it seems that all the conditions are checked with character class. I tried changing all instances of 'zero_VOC_2" to as.numeric(1) or TRUE and checking for those in the conditional but to no avail. Any assistance is appreciated!

CodePudding user response:

cols <- "a_Pinene","Isoprene","Methyl_Vinyl_Ketone", "Nopinone","Benzene_", "D_Limonene", "Sabinene","a_Cedrene","Pentane","Hexane")
x <- "2021-01-30"
y <- "2021-08-08"

# Replace values in original fields
slopejoin[slopejoin$tdiff == 2 & slopejoin$date >= x & slopejoin$date <= y,cols] <- slopejoin[slopejoin$tdiff == 2 & slopejoin$date >= x & slopejoin$date <= y,cols] * 0.85

  • Related