Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R应用返回的行,但需要列_R_Dataframe - Fatal编程技术网

R应用返回的行,但需要列

R应用返回的行,但需要列,r,dataframe,R,Dataframe,我试图清理调查数据,有时在小时字段中输入分钟信息。清洁规则规定,如果缺少分钟或0,小时数为15或30或45或60,则将小时值移动到分钟字段 以下是我编写的函数: cleanHrMin <- function(x){ h = x[1] m = x[2] if ( !is.na(h) && (h==15 || h==30 || h==45 || h==60) && (m==0 || is.na(m)) ) { return(c(0,h)) }

我试图清理调查数据,有时在小时字段中输入分钟信息。清洁规则规定,如果缺少分钟或0,小时数为15或30或45或60,则将小时值移动到分钟字段

以下是我编写的函数:

cleanHrMin <- function(x){
  h = x[1]
  m = x[2]
  if ( !is.na(h) && (h==15 || h==30 || h==45 || h==60) && (m==0 || is.na(m)) )
    { return(c(0,h)) }
  else
    { return(x) }
}
并获得输出:

  V1 V2 V3
1  1  0  0
2 10 15 15
但我想要的是:

  V1 V2
1  1 10
2  0 15
3  0 15

我做错了什么?

您做的是正确的跨行应用。您只需要转换输出

> as.data.frame(t(apply(df,1,cleanHrMin)))
  V1 V2
1  1 10
2  0 15
3  0 15
这是因为
apply
返回函数产生的列,无论您的边距是在行上还是在列上。所以,要从一行转到另一行,必须进行换位

  V1 V2
1  1 10
2  0 15
3  0 15
> as.data.frame(t(apply(df,1,cleanHrMin)))
  V1 V2
1  1 10
2  0 15
3  0 15