【问题标题】:Is the right function an R for finding row index of an elements from a vector in a data.frame?正确的函数是 R 用于从 data.frame 中的向量中查找元素的行索引吗?
【发布时间】:2019-03-25 18:47:27
【问题描述】:

在 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))
  }
}

【问题讨论】:

标签: r


【解决方案1】:
# 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

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 2022-12-13
    • 1970-01-01
    • 2017-04-15
    • 2021-08-17
    • 2016-10-27
    • 2014-09-03
    • 2022-11-30
    相关资源
    最近更新 更多