$ <-。data.frame`(`* tmp *`,newvar,value = numeric(0))错误:替换有0行,数据有139

时间:2018-07-22 23:46:28

标签: r

谁能告诉我为什么我的功能不起作用?不在函数中时,一切正常。请看下面:

<?xml version="1.0"?>
<uids>
    <!-- Some Unique Text -->
    <!-- VID_2564 -->
    <uid>1111</uid>
    <!-- Some Title -->
    <!-- VID_8374 -->
    <uid>2222</uid>
    <!-- Some Title -->
    <!-- VID_1128 -->
    <uid>3333</uid>
    <!-- A Different Title -->
    <!-- VID_9581 -->
    <uid>4444</uid>
</uids>

我得到的错误是:

scale.it<-function(df,var,newvar){

  varn <- as.numeric(df$var)

  last <- max(varn)

  df$newvar <- (varn/last)

  return(df)
}

scale.it(go.cubs.go,PAge,IPAge)

1 个答案:

答案 0 :(得分:0)

尝试一下:

scale.it<-function(df,var,newvar){

  varn <- as.numeric(df[, var])

  last <- max(varn)
  print(last)
  df[, newvar] <- (varn/last)

  return(df)
}


myDf <- data.frame(x = 1:5,y = 1:5)

scale.it(myDf,"x","xNew")
#   x y xNew
# 1 1 1  0.2
# 2 2 2  0.4
# 3 3 3  0.6
# 4 4 4  0.8
# 5 5 5  1.0

如果您使用varnewvar,将按字面解释df$vardf$newvar

话虽这么说,r中有一个名为scale的函数,它可以完成您在此所做的工作。例如,您可以执行以下操作:

myDf$xNewNew <- scale(myDf$x, center = F, scale = max(myDf$x))
#   x y xNewNew
# 1 1 1     0.2
# 2 2 2     0.4
# 3 3 3     0.6
# 4 4 4     0.8
# 5 5 5     1.0