![](/img/trans.png)
[英]r remove outliers from a list of data.frames and make a new list of data.frames?
[英]Create new list in R based on matching values from two data.frames
我有一個看起來像這樣的數據框:
df<-data.frame(x=c('x1','x2','x3','x4','x5'),y=c(1,2,3,4,5))
df2<-data.frame(x=c('x3','x5'),y=c(3,5))
df3<-merge(df,df2,by="x")
如何根據df
中的 x 值是否與df2
中的 x 值匹配來創建 0 和 1 的列表? 例如,新的數據框如下所示:
newdf<-data.frame(x=c('x1','x2','x3','x4','x5'),y=c(1,2,3,4,5),match=c(0,0,1,0,1)
使用data.table
(匹配x
和y
):
library(data.table)
setDT(df)
df[, match := 0L]
df[df2, on = .(x, y), match := 1L]
# x y match
# 1: x1 1 0
# 2: x2 2 0
# 3: x3 3 1
# 4: x4 4 0
# 5: x5 5 1
重新創建newdf
的base
解決方案:
newdf <- df
newdf$match <- ifelse(df$x %in% df2$x, 1, 0)
或者,使用tidyverse
語法:
library(tidyverse)
df %>%
mutate(match = ifelse(x %in% df2$x, 1, 0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.