【问题标题】:Multiply values of some columns of a data frame within a date range and based on the values of another column in R在日期范围内并基于 R 中另一列的值将数据框的某些列的值相乘
【发布时间】:2021-12-09 09:43:56
【问题描述】:

我正在为 R 中的 ifelse 语句而苦苦挣扎。我有一个包含 64 列和 12861 行的数据框。我需要在一个日期范围内(日期是一列)和基于另一行(tdiff)中的值相乘这些列中的 10 个,并将旧值替换为数据框中的新值。这行代码生成一个 12681 X 12681 的数据帧。它应该是 12681(行)乘 64(列)的原始大小。我究竟做错了什么?提前谢谢!

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")]))

编辑:我接受了第一个评论者的建议,但想再添加一个条件,但收到一个错误:“cols & slopejoin$substr 中的错误!= z: 只能对数字、逻辑或复杂类型进行操作。”这是我正在使用的代码:

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

不太清楚错误来自哪里。首先我在考虑一个类问题,但似乎所有条件都用字符类检查。我尝试将“zero_VOC_2”的所有实例更改为 as.numeric(1) 或 TRUE 并检查条件中的那些但无济于事。感谢任何帮助!

【问题讨论】:

    标签: r dataframe if-statement conditional-statements


    【解决方案1】:
    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
    
    

    【讨论】:

    • 谢谢!一个简单的问题:我想再添加一个条件:slopejoin$substr != z 其中 z 是 'zero_VOC_2'。但我收到错误:cols & slopejoin$substr != z 中的错误:操作只能用于数字、逻辑或复杂类型。我不明白为什么它会导致错误。你知道吗?
    • 不客气!当然,您使用的代码到底是什么? (您可以使用代码块更新您的原始问题)
    • 我已添加代码和完整的错误消息作为编辑!提前谢谢!
    • 看看这里以完善 R 中的方括号:rpubs.com/tomhopper/bracketsslopejoin[slopejoin$tdiff == 2 &amp; slopejoin$date &gt;= x &amp; slopejoin$date &lt;= y &amp; slopejoin$substr != z, cols] &lt;- slopejoin[slopejoin$tdiff == 2 &amp; slopejoin$date &gt;= x &amp; slopejoin$date &lt;= y &amp; slopejoin$substr != z, cols] * 0.06
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多