[英]Conditional replace row values for multiple columns based on subset of values in another column
Ok this should be simple and I am aware of many questions similar to this that have been answered but none of the answers are working for my data. 好的,这应该很简单,并且我知道已经回答了许多与此类似的问题,但是没有一个答案对我的数据有用。
Here is some quick example data to illustrate my point: 这是一些简单的示例数据来说明我的观点:
Soil <- c("Organic - 10", "Organic - 12", "Sand - 6", "Silt - 6", "Silt - 6")
Value1 <- c(2, 5, 1, 4, 6)
Value2 <- c(45, 21, 776, 2, 6)
X03 <- c(4, 23, 45, 12, 23)
X04 <- c(56, 2, 7, 34, 65)
DF <- data.frame(Soil, Value1, Value2, X03, X04)
Basically what I want to do is replace the values of X02 and X03 with 0 for the rows where Soil is "Organic". 基本上,我要为“土壤”为“有机”的行将X02和X03的值替换为0。
My initial thought was to do the following: 我最初的想法是执行以下操作:
# create index of the columns in whcih values are to be changed
index <- grep("^X0", colnames(DF))
# Use ifelse statement to change values conditionally
DF[,c(index)] <- ifelse(grepl("^Organic", DF$Soil), 0, DF[index])
This however gives the following warning and replaces all values with 0 in X03 and X04: 但是,这将给出以下警告,并在X03和X04中将所有值替换为0:
Warning message:
In `[<-.data.frame`(`*tmp*`, , c(index), value = list(0, 0, c(4, :
provided 5 variables to replace 2 variables
Any ideas appreciated. 任何想法表示赞赏。
尝试
DF[grepl("^Organic", DF$Soil),index]<-0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.