Return 来自用户定义函数的多个值
Return multiple values from a user defined function
我正在尝试在 R 中创建一个包含大约 5000 行和 5-6 列的虚拟数据集。我试图通过为每一列创建随机函数来实现它。然而调用函数 returns 只有一个值。我试图实现它的代码如下:-
Vertical <- function(a) {
vec1 <- c('HiTech', 'BFSI', 'Insurance', 'Retail', 'Ecomm', 'Media', 'Govt')
for(i in 1:a) {
b <- sample(vec1,1)
return(b)
}
}
n <- Vertical(5000)
我需要变量 'n' 到 return 的值范围(总共 5000),但我无法实现。请求一些帮助。
谢谢。
怎么样:
vec1 <- c('HiTech', 'BFSI', 'Insurance', 'Retail', 'Ecomm', 'Media', 'Govt')
b <- lapply(1:10, function(y) sample(vec1, y, replace=TRUE))
您可以将所有值一起采样并将它们放在 matrix/data.frame.
Vertical <- function(nr, nc) {
vec1 <- c('HiTech', 'BFSI', 'Insurance', 'Retail', 'Ecomm', 'Media', 'Govt')
as.data.frame(matrix(sample(vec1, nr * nc, replace = TRUE), nr, nc))
}
Vertical(6, 3)
# V1 V2 V3
#1 BFSI HiTech Govt
#2 Insurance Ecomm Insurance
#3 Media Govt Retail
#4 Ecomm Ecomm BFSI
#5 HiTech Govt Ecomm
#6 Govt Govt Retail
我正在尝试在 R 中创建一个包含大约 5000 行和 5-6 列的虚拟数据集。我试图通过为每一列创建随机函数来实现它。然而调用函数 returns 只有一个值。我试图实现它的代码如下:-
Vertical <- function(a) {
vec1 <- c('HiTech', 'BFSI', 'Insurance', 'Retail', 'Ecomm', 'Media', 'Govt')
for(i in 1:a) {
b <- sample(vec1,1)
return(b)
}
}
n <- Vertical(5000)
我需要变量 'n' 到 return 的值范围(总共 5000),但我无法实现。请求一些帮助。 谢谢。
怎么样:
vec1 <- c('HiTech', 'BFSI', 'Insurance', 'Retail', 'Ecomm', 'Media', 'Govt')
b <- lapply(1:10, function(y) sample(vec1, y, replace=TRUE))
您可以将所有值一起采样并将它们放在 matrix/data.frame.
Vertical <- function(nr, nc) {
vec1 <- c('HiTech', 'BFSI', 'Insurance', 'Retail', 'Ecomm', 'Media', 'Govt')
as.data.frame(matrix(sample(vec1, nr * nc, replace = TRUE), nr, nc))
}
Vertical(6, 3)
# V1 V2 V3
#1 BFSI HiTech Govt
#2 Insurance Ecomm Insurance
#3 Media Govt Retail
#4 Ecomm Ecomm BFSI
#5 HiTech Govt Ecomm
#6 Govt Govt Retail