在R中编写一个接收两个参数的函数。第一个是data.fame或data.table,第二个是整数向量。该函数的功能是在新的data.table或data.frame变量中返回其序列号在向量中的第一个参数的行。如果向量中的数字大于数据表中的行数,请针对该数字编写一条消息,指出输出中未包含该行。
我尝试过,但这不是向量,我不知道该怎么做
get_vecrow = function(data, vecrow){
if (vecrow <= nrow(data) & vecrow > 0){
print(data[vecrow,])
}
else{
print("Row: ")
print(nrow(data))
}
}
答案 0 :(得分:0)
# Dummy data
vector = c(1,2,10,400) # Vector of numbers want to find in df
df = data.frame(data = seq(1,100,1), random = "yee") # dummy df
# Loop to match vector numbers with data frame - on match save data frame row
grab_row = list() # Initialize output list
for (i in 1:nrow(df)){
if(df$data[i] %in% vector) { # Check that any number in the vector is in the data frame column
grab_row[[i]] = df[i,] # if TRUE, grab the data frame row
}
} # end
# Output df with rows that matched vector
out = do.call(rbind,grab_row)
对于输出
data random
1 1 yee
2 2 yee
10 10 yee