简体   繁体   English

基于另一列中的值子集的多个列的条件替换行值

[英]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.

相关问题 R数据表:使用条件列和另一列替换跨多列的行值子集 - R data table: replace subset of row values across multiple columns using conditional with another column 如何使用基于多列值的条件语句对 dataframe 进行子集化 - How to subset a dataframe with a conditional statement based on multiple column values 如何根据行值和列名替换列中的值? - How to replace values in columns based on row values and column names? R:将多列数据帧中的多个值替换为另一列中的值 - R: Replace multiple values in multiple columns of dataframes with values in another column 替换另一列中以is.na为条件的行值 - replace row values conditional on is.na in another column 如何用基于另一列的总和值替换df行中的值 - How to replace values in a row of a df with summed values based on another column 基于另一个数据表的多个列值对一个数据表上的行进行子集 - Subset rows on one datatable based on multiple column values of another datatable 根据前一列的值替换多列中的值 - Replace values in multiple columns based on values from preceding column 如何根据每行中 R 中的/另一列替换几列的值? - How to replace values of several columns based on/ another column in R within each row? 根据条件用另一列的值替换多列中的值 - Replace values in multiple columns by values of another column on condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM