R语言 如果两列匹配,则返回行(i)

oknwwptz  于 2023-09-27  发布在  其他
关注(0)|答案(4)|浏览(87)

我有两个数据集:
DF1

ID        paddock    cow ID
90/123    10         09/123
90/124    11         09/124
90/125    11         09/124

DF2

ID        paddock
09/123    20
09/124    21

我想将df1$cowID与df2$ID匹配,并返回df2$paddock,无论匹配的是哪一行。代码如下:

dt <- ifelse(df1$cowID %in% df2$ID, df2$paddock[i], NA)

但我得到了一个返回错误。有人能给我指个路吗?提前感谢!

kpbpu008

kpbpu0081#

你应该使用match

df1$df2_paddock <- df2$paddock[match(df1$cow_ID, df2$ID)]
df1

#      ID paddock cow_ID df2_paddock
#1 90/123      10 09/123          20
#2 90/124      11 09/124          21

数据

df1 <- structure(list(ID = structure(1:2, .Label = c("90/123", "90/124"
), class = "factor"), paddock = 10:11, cow_ID = structure(1:2, .Label = c("09/123", 
"09/124"), class = "factor")), class = "data.frame", row.names = c(NA, -2L))

df2 <- structure(list(ID = structure(1:2, .Label = c("09/123", "09/124"
), class = "factor"), paddock = 20:21), class = "data.frame", 
row.names = c(NA, -2L))
epggiuax

epggiuax2#

如果你想使用ifelse(),也许你可以使用下面的代码来实现它

with(df2,ifelse(ID %in% df1$cow_ID,paddock,NA))

使得

> with(df2,ifelse(ID %in% df1$cow_ID,paddock,NA))
[1] 20 21

资料

df1 <- structure(list(ID = structure(1:3, .Label = c("90/123", "90/124", 
"90/125"), class = "factor"), paddock = c(10, 11, 11), cow_ID = structure(c(1L, 
2L, 2L), .Label = c("09/123", "09/124"), class = "factor")), class = "data.frame", row.names = c(NA, 
-3L))

df2 <- structure(list(ID = structure(1:2, .Label = c("09/123", "09/124"
), class = "factor"), paddock = c(20, 21)), class = "data.frame", row.names = c(NA, 
-2L))
3gtaxfhh

3gtaxfhh3#

你可以通过连接两个 Dataframe 并获取你想要的列来实现。

使用Base R

df1 <-
  data.frame(
    ID = c("90/123", "90/124"),
    paddock = c(10, 11),
    cow_ID = c("09/123", "09/124")
  )

df2 <-
  data.frame(
    ID = c("90/123", "90/124"),
    paddock = c(20, 21)
  )

# Joining the two dataframes by ID then choosing column of interest
merge(df1, df2, by = c("ID"), suffixes = c(".x", ".y"))["paddock.y"]

# paddock.y
# 20
# 21

使用Dplyr

library(dplyr)

df1 <-
  data.frame(
    ID = c("90/123", "90/124"),
    paddock = c(10, 11),
    cow_ID = c("09/123", "09/124")
  )

df2 <-
  data.frame(
    ID = c("90/123", "90/124"),
    paddock = c(20, 21)
  )

# Joining the two dataframes by ID then choosing column of interest
df1 %>%
  inner_join(df2, by = c("ID"), suffixes = c(".x", ".y")) %>%
  select(paddock.y) %>%
  rename(paddock = paddock.y)

# paddock
# 20
# 21
goucqfw6

goucqfw64#

你可以考虑加入数据集。

dplyr::left_join(df1, df2, by = c('cow ID', 'ID')

相关问题