-1

我希望更新 r 中的列中的值,但它当前替换了它。

例如:

主题数据框:

 Maths | English | Science | History |  Class

 0.1    |  0.2   |  0.3    |  0.2    |   Y2

 0.9    |  0.5   |  0.7    |  0.4   |   Y1

这是我的代码,但目前,它仅将上面的数字替换为 1 并且不会添加到其中。

classpred$Maths[grepl("^Y9$",classpred$class)] <- 1

我想要这个输出:

 Maths | English | Science | History |  Class

 1.1    |  0.2   |  0.3    |  0.2    |   Y9

 0.9    |  0.5   |  0.7    |  0.4   |   Y10
4

1 回答 1

1

您在这里遇到的问题是分配问题。在您的情况下,运算符<-将 1 分配给索引值,而不是添加 1,这就是为什么 @hrbrmstr 解决方案通过更改<-+. 以这个简化的例子为例:

x <- c(2:10) #dummy sequence
x[3] # index 3rd value in sequence
x[3] <- 1 # replace 3rd value with 1
x # value that was 4 is now 1
x[3] <- x[3]+1 # index 3rd value and add 1 to that value
x # value that became 1 is now 2

如果您需要对大型数据集进行大量此类操作,您可能会发现 tidyverse 解决方案变得更容易,如下所示:

library(tidyverse)
class_df <- data.frame(maths = c(1,2,3),
                       english = c(3,2,1),
                       class = c("yr_9", "yr_10", "yr_11"))
class_df <- class_df %>%
  mutate(maths = case_when(class == "yr_9" ~ maths +1, TRUE ~ as.numeric(maths)))

查看此资源以获取信息https://jules32.github.io/2016-07-12-Oxford/dplyr_tidyr/

干杯!

于 2018-11-12T01:09:11.260 回答