R在不起作用的循环中填充数据框

时间:2016-05-10 04:37:45

标签: r for-loop dataframe

我找不到谷歌搜索中有效的答案。 我的数据框架没有填充我不知道为什么。这看起来很简单但不起作用。有人可以帮忙吗?

x<- 50:1
y<- -44:5

theDF <- data.frame(x,y)

# add new column
theDF["GName"] <- 'NA'

divToG <- function (a)
{
   counter = 1
   g_number = 1

   # loop to populate new column
   for (i in 1:nrow(theDF))
   {
      theDF$GName[i] = paste("GName", toString(g_number))  # NOT WORKING!
      g_number = g_number + 1
   }    
}

#call the function
divToG (theDF)

为什么不填充theDF$GName[i]?如果循环成功,则列应为GName 1GName 2Gname 3等,而不是NA,但我无法从NA更改

2 个答案:

答案 0 :(得分:2)

你需要在函数中输入return命令:

divToG <- function (a)
{
  counter = 1
  g_number = 1

  # loop to populate new column
  for (i in 1:nrow(theDF))
  {
    theDF$GName[i] = paste("GName", toString(g_number))  # NOT WORKING!
    g_number = g_number + 1
  }    
  return(theDF)
}

head(divToG (theDF))
   x   y   GName
1 50 -44 GName 1
2 49 -43 GName 2
3 48 -42 GName 3
4 47 -41 GName 4
5 46 -40 GName 5
6 45 -39 GName 6

更优雅的方法是取消该功能并运行:

theDF$GName <- paste("GName", 1:nrow(theDF))

答案 1 :(得分:0)

如果你:一个字符串到一个数字序列,数字将被强制转换为字符,字符串将被粘贴到每个字符串上。因此,第一步是按照seqsequence或偶尔rep的方式获得您想要的序列。如果您尝试制作分组变量,each的{​​{1}}参数会有所帮助:

rep(1:5, each = 3)
# [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5

现在只需paste一个前缀(此处paste0sep = ""):

paste0('GName', rep(1:5, each = 10))
#  [1] "GName1" "GName1" "GName1" "GName1" "GName1" "GName1" "GName1" "GName1" "GName1" "GName1"
# [11] "GName2" "GName2" "GName2" "GName2" "GName2" "GName2" "GName2" "GName2" "GName2" "GName2"
# [21] "GName3" "GName3" "GName3" "GName3" "GName3" "GName3" "GName3" "GName3" "GName3" "GName3"
# [31] "GName4" "GName4" "GName4" "GName4" "GName4" "GName4" "GName4" "GName4" "GName4" "GName4"
# [41] "GName5" "GName5" "GName5" "GName5" "GName5" "GName5" "GName5" "GName5" "GName5" "GName5"