从上一个创建一个新的df,将2列与R合并为一个

问题描述 投票:0回答:1

大家好,我希望你一切都好!

我需要帮助ID才能从先前的df1创建另一个df2。

这里是df1:

Query               Target  Val1   Val2
Segm1_Z_-__SP1_A    XP_0001 1      0.009
Segm1_Y_+__SP1_A    XP_0001 1      0.010
Segm3_Z_-__SP2_A    XP_0001 1      0.011
Segm3_K_-__SP2_B    XP_0002 0      0.012
Segm1_Z_+__SP3_A    XP_0002 1      0.013

而且我想用new_col替换df2来替换QueryTarget

;

New_col             Val1    Val2
Segm1_Z_-__SP1_A    1       0.009
Segm1_Y_+__SP1_A    1       0.010
Segm3_Z_-__SP2_A    1       0.011
Segm3_K_-__SP2_B    0       0.012
Segm1_Z_+__SP3_A    1       0.013
XP_0001             NA      NA
XP_0002             NA      NA

有人有想法吗?

r
1个回答
1
投票

您的意思是这样的吗?

dplyr::bind_rows(df,data.frame(Query=unique(df$Target),stringsAsFactors = FALSE))

#             Query  Target Val1  Val2
#1 Segm1_Z_-__SP1_A XP_0001    1 0.009
#2 Segm1_Y_+__SP1_A XP_0001    1 0.010
#3 Segm3_Z_-__SP2_A XP_0001    1 0.011
#4 Segm3_K_-__SP2_B XP_0002    0 0.012
#5 Segm1_Z_+__SP3_A XP_0002    1 0.013
#6          XP_0001    <NA>   NA    NA
#7          XP_0002    <NA>   NA    NA

数据

df <- structure(list(Query = c("Segm1_Z_-__SP1_A", "Segm1_Y_+__SP1_A", 
"Segm3_Z_-__SP2_A", "Segm3_K_-__SP2_B", "Segm1_Z_+__SP3_A"), 
Target = c("XP_0001", "XP_0001", "XP_0001", "XP_0002", "XP_0002"
), Val1 = c(1L, 1L, 1L, 0L, 1L), Val2 = c(0.009, 0.01, 0.011, 
0.012, 0.013)), row.names = c(NA, -5L), class = "data.frame")
© www.soinside.com 2019 - 2024. All rights reserved.