我找不到谷歌搜索中有效的答案。 我的数据框架没有填充我不知道为什么。这看起来很简单但不起作用。有人可以帮忙吗?
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 1
,GName 2
,Gname 3
等,而不是NA
,但我无法从NA
更改
答案 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)
如果你:
一个字符串到一个数字序列,数字将被强制转换为字符,字符串将被粘贴到每个字符串上。因此,第一步是按照seq
,sequence
或偶尔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
一个前缀(此处paste0
为sep = ""
):
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"