根据另一列中的值子集有条件地替换多列的行值

时间:2014-12-03 16:57:09

标签: r row conditional

好的,这应该很简单,我知道很多类似的问题已经得到解答,但没有一个答案适用于我的数据。

以下是一些快速示例数据来说明我的观点:

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)

基本上我想做的是将X02和X03的值替换为0,其中的土壤是&#34;有机&#34;。

我最初的想法是做以下事情:

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

然而,这会发出以下警告,并将所有值替换为X03和X04中的0:

Warning message:
In `[<-.data.frame`(`*tmp*`, , c(index), value = list(0, 0, c(4,  :
  provided 5 variables to replace 2 variables

任何想法都赞赏。

1 个答案:

答案 0 :(得分:1)

尝试

DF[grepl("^Organic", DF$Soil),index]<-0
相关问题