簡體   English   中英

在值列表之后,我想對 r 中的數據框進行子集化,其中行包含某列中的值

[英]Following a list of values, I want to subset a data frame in r with rows containing the values in a certain column

我有一個數據框,想提取值與某個向量一致的行。 在df中,沒有重復。 我需要數據框來保持向量的順序。

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)

mydf <- data.frame(Name, Age)

myvector <- c(23, 26, 32, 26) 

我的預期答案是

"Jon", "Tina", "Maria", "Tina"

這是我嘗試過的事情之一:

> df[df$Age == to_find,]$Name
Warning message:
In df$Age == to_find :
  longer object length is not a multiple of shorter object length

此外,下一個解決方案並沒有給我所有預期的行,並且仍然給我一條錯誤消息:

> subset(df, Age == to_find)
   Name Age
1   Jon  23
3 Maria  32
Warning message:
In Age == to_find :
  longer object length is not a multiple of shorter object length

謝謝您的幫助!

下面的 for 循環返回您想要的 output。 它還基於原始數據集中沒有兩個人的年齡相同的假設。 如果是這種情況,它只會獲取數據集中第一個與年齡匹配的人的姓名。 例如,如果 'myvector' 正在尋找 34 歲的人,並且 mydf 中有兩個人,即 34 歲的 Joseph 和 Brian,則新的 'names' 向量將僅從數據集中獲取與年齡匹配的第一個人的姓名34,不管你找了多少次34。

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)

mydf <- data.frame(Name, Age)

myvector <- c(23, 26, 32, 26)

names <- vector(mode="character", length=length(myvector))

for (i in 1:length(names)) {
  
  for (j in 1:length(mydf$Name)) {
    
    if(mydf$Age[j] == myvector[i]) {
      names[i] <- mydf$Name[j]
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM