[英]Following a list of values, I want to subset a data frame in r with rows containing the values in a certain column
I have a data frame and want to extract the rows that the value coincide with a certain vector.我有一个数据框,想提取值与某个向量一致的行。 In the df, there are no duplicate.在df中,没有重复。 I need the data frame to keep the order of the vector.我需要数据框来保持向量的顺序。
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)
My expected answer would be我的预期答案是
"Jon", "Tina", "Maria", "Tina"
This is one of the things I've tried:这是我尝试过的事情之一:
> df[df$Age == to_find,]$Name
Warning message:
In df$Age == to_find :
longer object length is not a multiple of shorter object length
Also this next solution doesn't give me all the expected rows and still gives me an error message:此外,下一个解决方案并没有给我所有预期的行,并且仍然给我一条错误消息:
> 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
Thank you for your help!谢谢您的帮助!
The for loop below returns your desired output.下面的 for 循环返回您想要的 output。 It is also based on the assumption that no two people in your original dataset will have the same age.它还基于原始数据集中没有两个人的年龄相同的假设。 If that is the case, it simply gets the name of the first person in your dataset who matches the age.如果是这种情况,它只会获取数据集中第一个与年龄匹配的人的姓名。 For example, if 'myvector' is looking for people aged 34, and there are two people, Joseph and Brian aged 34 in mydf, the new 'names' vector will only get the name of the first person from the dataset who matches the age 34, regardless of how many times you look for 34.例如,如果 '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.