测试特定的列/行名称是否为r

时间:2018-07-03 14:21:34

标签: r for-loop if-statement dataframe

我正在尝试测试列是否被命名为特定的名称(然后我想对行名称执行相同的操作)。因此,可以遍历每个列名以查看是否相等吗?

示例:

dataframe:
      Jan     Feb     Mar
Jan    0       0       0
Feb    0       0       0
Mar    0       0       0

逻辑:遍历每一列以查找是否称为“ Jan”,并遍历每一行以查看是否称为“ Feb”。如果满足逻辑,则在等效的行/行中放入1。例如

Final dataframe:
       Jan     Feb     Mar
Jan    0       0       0
Feb    1       0       0
Mar    0       0       0

谢谢!

1 个答案:

答案 0 :(得分:0)

我生成了如下数据:

df<-data.frame("Jan" = rep(x = 0,times = 3),"Feb" = rep(x = 0,times = 3),"Mar" = rep(x = 0,times = 3))
rownames(df)<-c("Jan","Feb","Mar")

这将提供以下数据框:

    Jan Feb Mar
Jan   0   0   0
Feb   0   0   0
Mar   0   0   0

以下显式函数应为您提供帮助:

set_func<-function(dt,col,row){
  nm_col<-colnames(dt)
  nm_row<-rownames(dt)
  if(col %in% nm_col){
    col_id<-which(nm_col == col)
  }
  else {
    cat(col,"is not present as a column name in the input data\n")
  }
  if(row %in% nm_row){
    row_id<-which(nm_row == row)
  }
  else {
    cat(row,"is not present as a row name in the input data\n")
  }
  if(exists("col_id") == T & exists("row_id") == T){
    dt[row_id,col_id]<-1
  }
  return(dt)
}

该函数的参数为​​:

dt-您的输入数据框
col-您正在检查的列名称中的值
row-您要在行名中检查的值

在您的示例中使用此功能可获得以下结果:

> set_func(dt = df,col = "Jan",row = "Feb")
    Jan Feb Mar
Jan   0   0   0
Feb   1   0   0
Mar   0   0   0

但是,如果您检查不存在作为列名或行名的值,则会显示一条消息,通知您该值不存在。

> set_func(dt = df,col = "Apr",row = "Mar")
Apr is not present as a column in the input data
    Jan Feb Mar
Jan   0   0   0
Feb   0   0   0
Mar   0   0   0