简体   繁体   English

匹配/子集一个 dataframe 基于另一个 dataframe 中的条件值在 R

[英]Match/subset one dataframe based on conditional values in another dataframe in R

I have two data frames:我有两个数据框:

df1=data.frame(A=c(1,2,4,8), B=c(4,3,2,9), C=c(10,11,1,2), D=c(12,40,3,4))
df2=data.frame(A=c(0.5,2.0,0.1,0.3), B=c(1.5,0.5,0.2,0.1), C=c(3.0,1.25,0.5,0.2), D=c(0.7,0.8,0.2,2.0))

I want to keep values in df1 that are <= 0.8 in df1 for all columns and NA s in the ones that are > 0.8我想在 df1 中为所有列保留 <= 0.8 的值,在 > 0.8 的列中保留NA

I tried to find and replace values > 0.8 in df2:我试图在 df2 中查找和替换 > 0.8 的值:

df2[df2 >= 0.8] <- NA

Then I tried to replace all matching values in df1 with the NA in df2 but something like the script below wants columns not dataframes:然后我尝试用 df2 中的NA替换 df1 中的所有匹配值,但类似于下面的脚本需要列而不是数据框:

df1[match(df1, df2==NA)] 

I want the final dataframe to look like this:我希望最终的 dataframe 看起来像这样:

df3=data.frame(A=c(1,NA,4,8), B=c(NA,3,2,9), C=c(NA,NA,1,2), D=c(12,40,3,NA))

TIA TIA

Use mapply like this:像这样使用mapply

as.data.frame(mapply(function(x, y) ifelse(y <= 0.8, x, NA), df1, df2))

or或者

replace(df1, df2 > 0.8, NA)

We can directly assign NA based on the logical matrix我们可以根据逻辑矩阵直接分配NA

 NA^(df2 > 0.8) * df1

or或者

`is.na<-`(df1, df2 > 0.8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用另一个R数据帧的值对一个R数据帧进行子集化? - How to subset one R dataframe with the values of another R dataframe? r - 如何基于另一个 dataframe 对 dataframe 进行子集化 - r - How to subset a dataframe based on another dataframe 使用 case_when() 和 filter() 根据 R 中一列中的值和另一列中的级别对数​​据框进行子集化 - using case_when() and filter() to subset a dataframe based on values in one column and levels in another column in R 如果在基于另一帧的数据帧上则为条件 - Conditional if on a dataframe based on another one 如何根据另一个数据对 R 中的数据帧进行子集化 - How to subset dataframe in R based on another data 2个变量与R中的另一个数据框匹配的数据框的子集 - Subset of dataframe for which 2 variables match another dataframe in R 如何根据与另一个 dataframe 匹配的列对 dataframe 进行子集化? - How to subset a dataframe based on columns that match another dataframe? 如何基于R中的另一个数据框过滤和子集数据框 - How to filter and subset a dataframe based on another dataframe in R R-根据来自另一个数据框的条件对一个数据框进行子集 - R - Subset a dataframe based on condition from another dataframe 使用 R 数据帧中的值作为索引来子集和汇总另一个数据帧? - Use values in R dataframe as index to subset and summarize another dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM