我有两个大的数据帧,一个( df1
)具有这种结构
chr init
1 12 25289552
2 3 180418785
3 3 180434779
其他( df2
)有这
V1 V2 V3
10 1 69094 medium
11 1 69094 medium
12 12 25289552 high
13 1 69095 medium
14 3 180418785 medium
15 3 180434779 low
我想要做的就是添加列V3
的df2
到df1
,得到突变的信息
chr init Mut
1 12 25289552 high
2 3 180418785 medium
3 3 180434779 low
我试图同时装入成R,然后用比赛做一个for循环,但它不工作。 你知道任何特殊的方式来做到这一点? 我也开用awk或类似的东西做
使用merge
df1 <- read.table(text=' chr init
1 12 25289552
2 3 180418785
3 3 180434779', header=TRUE)
df2 <- read.table(text=' V1 V2 V3
10 1 69094 medium
11 1 69094 medium
12 12 25289552 high
13 1 69095 medium
14 3 180418785 medium
15 3 180434779 low', header=TRUE)
merge(df1, df2, by.x='init', by.y='V2') # this works!
init chr V1 V3
1 25289552 12 12 high
2 180418785 3 3 medium
3 180434779 3 3 low
为了让您所需的输出,你表现出来的方式
output <- merge(df1, df2, by.x='init', by.y='V2')[, c(2,1,4)]
colnames(output)[3] <- 'Mut'
output
chr init Mut
1 12 25289552 high
2 3 180418785 medium
3 3 180434779 low
df1 <- read.table(textConnection(" chr init
1 12 25289552
2 3 180418785
3 3 180434779"), header=T)
df2 <- read.table(textConnection(" V1 V2 V3
10 1 69094 medium
11 1 69094 medium
12 12 25289552 high
13 1 69095 medium
14 3 180418785 medium
15 3 180434779 low"), header=T)
# You have to select the values of df2$V3 such as their corresponding V2
# are equal to the values of df1$init
df1$Mut <- df2$V3[ df2$V2 %in% df1$init]
df1
chr init Mut
1 12 25289552 high
2 3 180418785 medium
3 3 180434779 low
是否
df3 <- merge( df1, df2, by.x = "init", by.y = "V2" )
df3 <- df3[-3]
colnames( df3 )[3] <- "Mut"
给你你想要什么?
@ user976991评论为我工作。
同样的想法,但需要匹配的两列。
我的域环境是一个产品数据库具有多个条目(潜在的价格条目)。 要删除旧的update_nums,只保留最新的PRODUCT_ID。
raw_data <- data.table( product_id = sample(10:13, 20, TRUE), update_num = sample(1:3, 20, TRUE), stuff = rep(1, 20, sep = ''))
max_update_nums <- raw_data[ , max(update_num), by = product_id]
distinct(merge(dt, max_update_nums, by.x = c("product_id", "update_num"), by.y = c("product_id", "V1")))
文章来源: Matching multiple columns on different data frames and getting other column as result